nuqs exposes the createParser{:ts} function to make your own parsers.
Creating a parser
You passcreateParser{:ts} two required functions:
parse{:ts}: a function that takes a string and returns the parsed value, ornull{:ts}if invalid.serialize{:ts}: a function that takes the parsed value and returns a string.
The
parse{:ts} function should always return null{:ts} for invalid inputs.
Never throw an error from the parse function.Hex color parser example
Here’s a practical example of a parser that handles hex color values:Equality function
For state types that can’t be compared by the==={:ts} operator, you’ll need to
provide an eq{:ts} function as well:
clearOnDefault{:ts} option,
to check if the current value is equal to the default value.
Multi Parsers
The parsers we’ve seen until now areSingleParsers{:ts}: they operate on the first occurence of the
key in the URL, and give you a string value to parse when it’s available.
MultiParsers{:ts} work similar to SingleParsers{:ts}, except that they operate on arrays, to support key repetition:
parse{:ts}takes anArray<string>{:ts}. It receives all matching values of the key it operates on, and returns the parsed value, ornull{:ts}if invalid.serialize{:ts}takes the parsed value and returns anArray<string>{:ts}, where each item will be separately added to the URL.
Builder pattern
Parsers created withcreateParser{:ts} have access to the builder pattern,
allowing you to chain configuration methods:
Testing custom parsers
Parsers should be bijective:parse(serialize(x)) === x{:ts} and serialize(parse(x)) === x{:ts}.
To help test bijectivity, you can use helpers defined in nuqs/testing: