Skip to content

Commit e3016ce

Browse files
committed
fix: Use TanStack Router default stringify for search params (#1127)
1 parent a2ad790 commit e3016ce

1 file changed

Lines changed: 13 additions & 20 deletions

File tree

packages/nuqs/src/adapters/tanstack-router.ts

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1-
import { useLocation, useMatches, useNavigate } from '@tanstack/react-router'
1+
import {
2+
stringifySearchWith,
3+
useLocation,
4+
useMatches,
5+
useNavigate
6+
} from '@tanstack/react-router'
27
import { startTransition, useCallback, useMemo } from 'react'
38
import { renderQueryString } from '../lib/url-encoding'
49
import { createAdapterProvider, type AdapterProvider } from './lib/context'
510
import type { AdapterInterface, UpdateUrlFunction } from './lib/defs'
611

12+
// Use TanStack Router's default JSON-based search param serialization
13+
const defaultStringifySearch = stringifySearchWith(JSON.stringify)
14+
715
function useNuqsTanstackRouterAdapter(watchKeys: string[]): AdapterInterface {
816
const search = useLocation({
917
select: state =>
@@ -20,25 +28,10 @@ function useNuqsTanstackRouterAdapter(watchKeys: string[]): AdapterInterface {
2028
})
2129
const searchParams = useMemo(
2230
() =>
23-
// search is a Record<string, string | number | object | Array<string | number>>,
24-
// so we need to flatten it into a list of key/value pairs,
25-
// replicating keys that have multiple values before passing it
26-
// to URLSearchParams, otherwise { foo: ['bar', 'baz'] }
27-
// ends up as { foo → 'bar,baz' } instead of { foo → 'bar', foo → 'baz' }
28-
new URLSearchParams(
29-
Object.entries(search).flatMap(([key, value]) => {
30-
if (Array.isArray(value)) {
31-
return value.map(v => [key, v])
32-
} else if (typeof value === 'object' && value !== null) {
33-
// TSR JSON.parses objects in the search params,
34-
// but parseAsJson expects a JSON string,
35-
// so we need to re-stringify it first.
36-
return [[key, JSON.stringify(value)]]
37-
} else {
38-
return [[key, value]]
39-
}
40-
})
41-
),
31+
// Use TSR’s default stringify to convert search object → URLSearchParams.
32+
// This avoids issues where arrays/objects were previously flattened
33+
// into invalid values like "[object Object]".
34+
new URLSearchParams(defaultStringifySearch(search)),
4235
[search, watchKeys.join(',')]
4336
)
4437

0 commit comments

Comments
 (0)