Skip to content

Commit

Permalink
fix: Handle clearOnDefault in createSerializer
Browse files Browse the repository at this point in the history
  • Loading branch information
hugotiger committed Sep 19, 2024
1 parent 97a1ea8 commit f6ca270
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
31 changes: 30 additions & 1 deletion packages/nuqs/src/serializer.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { describe, expect, test } from 'vitest'
import { parseAsBoolean, parseAsInteger, parseAsString } from './parsers'
import {
parseAsBoolean,
parseAsInteger,
parseAsString,
parseAsJson,
parseAsArrayOf
} from './parsers'
import { createSerializer } from './serializer'

const parsers = {
Expand Down Expand Up @@ -62,4 +68,27 @@ describe('serializer', () => {
const result = serialize('?str=bar&int=-1', { str: 'foo', int: null })
expect(result).toBe('?str=foo')
})
test('clears value when setting the default value when `clearOnDefault` is used', () => {
const serialize = createSerializer({
int: parseAsInteger.withOptions({ clearOnDefault: true }).withDefault(0),
str: parseAsString.withOptions({ clearOnDefault: true }).withDefault(''),
bool: parseAsBoolean
.withOptions({ clearOnDefault: true })
.withDefault(false),
arr: parseAsArrayOf(parseAsString)
.withOptions({ clearOnDefault: true })
.withDefault([]),
json: parseAsJson()
.withOptions({ clearOnDefault: true })
.withDefault({ foo: 'bar' })
})
const result = serialize({
int: 0,
str: '',
bool: false,
arr: [],
json: { foo: 'bar' }
})
expect(result).toBe('')
})
})
8 changes: 7 additions & 1 deletion packages/nuqs/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,13 @@ export function createSerializer<
if (!parser || value === undefined) {
continue
}
if (value === null) {
const isMatchingDefault =
// @ts-expect-error
parser.defaultValue !== undefined &&
// @ts-expect-error
(parser.eq ?? ((a, b) => a === b))(value, parser.defaultValue)

if (value === null || (parser.clearOnDefault && isMatchingDefault)) {
search.delete(key)
} else {
search.set(key, parser.serialize(value))
Expand Down

0 comments on commit f6ca270

Please sign in to comment.