Skip to content

Commit

Permalink
fix: Allow serializers to operate on derived UrlSearchParams classes (
Browse files Browse the repository at this point in the history
#647)

* Create a copy of `UrlSearchParams` when used as the base for a serializer

Follow-up to #646

* Update packages/nuqs/src/serializer.ts

Co-authored-by: François Best <github@francoisbest.com>

* test: Add test to show that existing params are not mutated

* chore: Fix formatting

---------

Co-authored-by: François Best <github@francoisbest.com>
  • Loading branch information
neefrehman and franky47 committed Sep 25, 2024
1 parent 576e754 commit 5dbbb1d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 7 additions & 0 deletions packages/nuqs/src/serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ describe('serializer', () => {
const result = serialize(search, { str: 'foo' })
expect(result).toBe('?bar=egg&str=foo')
})
test('Does not mutate existing params with URLSearchParams base', () => {
const serialize = createSerializer(parsers)
const searchBefore = new URLSearchParams('?str=foo')
const result = serialize(searchBefore, { str: 'bar' })
expect(result).toBe('?str=bar')
expect(searchBefore.get('str')).toBe('foo')
})
test('with URL base', () => {
const serialize = createSerializer(parsers)
const url = new URL('https://example.com/path')
Expand Down
7 changes: 5 additions & 2 deletions packages/nuqs/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,11 @@ function splitBase(base: Base) {
const [path = '', search] = base.split('?')
return [path, new URLSearchParams(search)] as const
} else if (base instanceof URLSearchParams) {
return ['', base] as const
return ['', new URLSearchParams(base)] as const // Operate on a copy of URLSearchParams, as derived classes may restrict its allowed methods
} else {
return [base.origin + base.pathname, base.searchParams] as const
return [
base.origin + base.pathname,
new URLSearchParams(base.searchParams)
] as const
}
}

0 comments on commit 5dbbb1d

Please sign in to comment.