Skip to content

Commit

Permalink
fix: Default value on server-side parsing
Browse files Browse the repository at this point in the history
Closes #384.
  • Loading branch information
franky47 committed Nov 2, 2023
1 parent dab4730 commit 45029d4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
14 changes: 14 additions & 0 deletions packages/next-usequerystate/src/parsers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,18 @@ describe('parsers', () => {
// It encodes its separator
expect(parser.serialize(['a', ',', 'b'])).toBe('a,%2C,b')
})

test('parseServerSide with default (#384)', () => {
const p = parseAsString.withDefault('default')
const searchParams = {
string: 'foo',
stringArray: ['bar', 'egg'],
undef: undefined
}
expect(p.parseServerSide(searchParams.undef)).toBe('default')
expect(p.parseServerSide(searchParams.string)).toBe('foo')
expect(p.parseServerSide(searchParams.stringArray)).toBe('bar')
// @ts-expect-error - Implicitly undefined
expect(p.parseServerSide(searchParams.nope)).toBe('default')
})
})
7 changes: 5 additions & 2 deletions packages/next-usequerystate/src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ export type ParserBuilder<T> = Required<Parser<T>> &
export function createParser<T>(parser: Required<Parser<T>>): ParserBuilder<T> {
return {
...parser,
parseServerSide(value = '') {
parseServerSide(value) {
if (typeof value === 'undefined') {
return null
}
let str = ''
if (Array.isArray(value)) {
// Follow the spec:
Expand All @@ -94,7 +97,7 @@ export function createParser<T>(parser: Required<Parser<T>>): ParserBuilder<T> {
return {
...this,
defaultValue,
parseServerSide(value = '') {
parseServerSide(value) {
return nullableParse(value) ?? defaultValue
}
}
Expand Down

0 comments on commit 45029d4

Please sign in to comment.