Skip to content

Commit

Permalink
feat(serializer): allow null to clear all param values from base (#657
Browse files Browse the repository at this point in the history
)

* feat(serializer): allow `null` to clear all param values from base

* test: Add test to show that externally managed params are kept

* chore: Apply formatting

I wish the GitHub suggestions UI could do this..

---------

Co-authored-by: Francois Best <[email protected]>
  • Loading branch information
neefrehman and franky47 authored Sep 27, 2024
1 parent 8cbae4f commit 0e7395e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
12 changes: 11 additions & 1 deletion packages/nuqs/src/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,21 @@ describe('serializer', () => {
const result = serialize(url, { str: 'foo' })
expect(result).toBe('https://example.com/path?bar=egg&str=foo')
})
test('null deletes from base', () => {
test('null value deletes from base', () => {
const serialize = createSerializer(parsers)
const result = serialize('?str=bar&int=-1', { str: 'foo', int: null })
expect(result).toBe('?str=foo')
})
test('null deletes all from base', () => {
const serialize = createSerializer(parsers)
const result = serialize('?str=bar&int=-1', null)
expect(result).toBe('')
})
test('null keeps search params not managed by the serializer', () => {
const serialize = createSerializer(parsers)
const result = serialize('?str=foo&external=kept', null)
expect(result).toBe('?external=kept')
})
test('clears value when setting the default value when `clearOnDefault` is used', () => {
const serialize = createSerializer({
int: parseAsInteger.withOptions({ clearOnDefault: true }).withDefault(0),
Expand Down
12 changes: 9 additions & 3 deletions packages/nuqs/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,21 @@ export function createSerializer<
* - another value is given for an existing key, in which case the
* search param will be updated
*/
function serialize(base: Base, values: Values<Parsers>): string
function serialize(base: Base, values: Values<Parsers> | null): string
function serialize(
baseOrValues: Base | Values<Parsers>,
values: Values<Parsers> = {}
baseOrValues: Base | Values<Parsers> | null,
values: Values<Parsers> | null = {}
) {
const [base, search] = isBase(baseOrValues)
? splitBase(baseOrValues)
: ['', new URLSearchParams()]
const vals = isBase(baseOrValues) ? values : baseOrValues
if (vals === null) {
for (const key in parsers) {
search.delete(key)
}
return base + renderQueryString(search)
}
for (const key in parsers) {
const parser = parsers[key]
const value = vals[key]
Expand Down

0 comments on commit 0e7395e

Please sign in to comment.