Skip to content

Commit df8f847

Browse files
committedJan 23, 2025
fix: Dynamic keys for useQueryStates
1 parent 894e141 commit df8f847

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed
 

Diff for: ‎packages/nuqs/src/useQueryStates.ts

+24-10
Original file line numberDiff line numberDiff line change
@@ -81,20 +81,11 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
8181
Object.fromEntries(
8282
Object.keys(keyMap).map(key => [key, urlKeys[key] ?? key])
8383
),
84-
[stateKeys, urlKeys]
84+
[stateKeys, JSON.stringify(urlKeys)]
8585
)
8686
const adapter = useAdapter()
8787
const initialSearchParams = adapter.searchParams
8888
const queryRef = useRef<Record<string, string | null>>({})
89-
// Initialise the queryRef with the initial values
90-
if (Object.keys(queryRef.current).length !== Object.keys(keyMap).length) {
91-
queryRef.current = Object.fromEntries(
92-
Object.values(resolvedUrlKeys).map(urlKey => [
93-
urlKey,
94-
initialSearchParams?.get(urlKey) ?? null
95-
])
96-
)
97-
}
9889
const defaultValues = useMemo(
9990
() =>
10091
Object.fromEntries(
@@ -119,6 +110,29 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
119110
internalState,
120111
initialSearchParams
121112
)
113+
// Initialise the refs with the initial values
114+
if (
115+
Object.keys(queryRef.current).join('&') !==
116+
Object.values(resolvedUrlKeys).join('&')
117+
) {
118+
const { state, hasChanged } = parseMap(
119+
keyMap,
120+
urlKeys,
121+
initialSearchParams,
122+
queryRef.current,
123+
stateRef.current
124+
)
125+
if (hasChanged) {
126+
stateRef.current = state
127+
setInternalState(state)
128+
}
129+
queryRef.current = Object.fromEntries(
130+
Object.values(resolvedUrlKeys).map(urlKey => [
131+
urlKey,
132+
initialSearchParams?.get(urlKey) ?? null
133+
])
134+
)
135+
}
122136

123137
useEffect(() => {
124138
const { state, hasChanged } = parseMap(

0 commit comments

Comments
 (0)