Skip to content

Commit 6d6d930

Browse files
committed
feat: Allow the serialize function in parsers to remove their key from the URL
Returning `null` from the `serialize` function signals that the associated search param should be removed from the URL.
1 parent 672aa53 commit 6d6d930

File tree

3 files changed

+16
-9
lines changed

3 files changed

+16
-9
lines changed

packages/nuqs/src/parsers.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@ export type Parser<T> = {
1414

1515
/**
1616
* Render the state value into a query string value.
17+
*
18+
* Return `null` to remove the query parameter from the URL.
1719
*/
18-
serialize?: (value: T) => string
20+
serialize?: (value: T) => string | null
1921

2022
/**
2123
* Check if two state values are equal.
@@ -94,7 +96,7 @@ export type ParserBuilder<T> = Required<Parser<T>> &
9496
* you can pass to one of the hooks, making its default value type safe.
9597
*/
9698
export function createParser<T>(
97-
parser: Require<Parser<T>, 'parse' | 'serialize'>
99+
parser: Require<Parser<T>, 'parse'>
98100
): ParserBuilder<T> {
99101
function parseServerSideNullable(value: string | string[] | undefined) {
100102
if (typeof value === 'undefined') {
@@ -117,6 +119,7 @@ export function createParser<T>(
117119

118120
return {
119121
eq: (a, b) => a === b,
122+
serialize: String,
120123
...parser,
121124
parseServerSide: parseServerSideNullable,
122125
withDefault(defaultValue) {
@@ -401,12 +404,11 @@ export function parseAsArrayOf<ItemType>(
401404
},
402405
serialize: values =>
403406
values
404-
.map<string>(value => {
405-
const str = itemParser.serialize
406-
? itemParser.serialize(value)
407-
: String(value)
408-
return str.replaceAll(separator, encodedSeparator)
407+
.map<string | null>(value => {
408+
const str = (itemParser.serialize ?? String)(value)
409+
return str?.replaceAll(separator, encodedSeparator) ?? null
409410
})
411+
.filter(value => value !== null)
410412
.join(separator),
411413
eq(a, b) {
412414
if (a === b) {

packages/nuqs/src/serializer.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ export function createSerializer<
6363
) {
6464
search.delete(urlKey)
6565
} else {
66-
search.set(urlKey, parser.serialize(value))
66+
const serialized = parser.serialize(value)
67+
if (serialized === null) {
68+
search.delete(urlKey)
69+
} else {
70+
search.set(urlKey, serialized)
71+
}
6772
}
6873
}
6974
return base + renderQueryString(search)

packages/nuqs/src/update-queue.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export function resetQueue() {
3737
export function enqueueQueryStringUpdate<Value>(
3838
key: string,
3939
value: Value | null,
40-
serialize: (value: Value) => string,
40+
serialize: (value: Value) => string | null,
4141
options: Pick<
4242
Options,
4343
'history' | 'scroll' | 'shallow' | 'startTransition' | 'throttleMs'

0 commit comments

Comments
 (0)