Skip to content

Commit

Permalink
fix: Read queued updates when initialising state
Browse files Browse the repository at this point in the history
Closes #702.
  • Loading branch information
franky47 committed Oct 23, 2024
1 parent 60cb4d8 commit c7aafab
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
4 changes: 4 additions & 0 deletions packages/nuqs/src/update-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ const transitionsQueue: Set<React.TransitionStartFunction> = new Set()
let lastFlushTimestamp = 0
let flushPromiseCache: Promise<URLSearchParams> | null = null

export function getQueuedValue(key: string) {
return updateQueue.get(key)
}

export function enqueueQueryStringUpdate<Value>(
key: string,
value: Value | null,
Expand Down
7 changes: 6 additions & 1 deletion packages/nuqs/src/useQueryState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { emitter, type CrossHookSyncPayload } from './sync'
import {
FLUSH_RATE_LIMIT_MS,
enqueueQueryStringUpdate,
getQueuedValue,
scheduleFlushToURL
} from './update-queue'
import { safeParse } from './utils'
Expand Down Expand Up @@ -235,7 +236,11 @@ export function useQueryState<T = string>(
} = useAdapter()
const queryRef = useRef<string | null>(initialSearchParams?.get(key) ?? null)
const [internalState, setInternalState] = useState<T | null>(() => {
const query = initialSearchParams?.get(key) ?? null
const queuedQuery = getQueuedValue(key)
const query =
queuedQuery === undefined
? (initialSearchParams?.get(key) ?? null)
: queuedQuery
return query === null ? null : safeParse(parse, query, key)
})
const stateRef = useRef(internalState)
Expand Down
7 changes: 6 additions & 1 deletion packages/nuqs/src/useQueryStates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { emitter, type CrossHookSyncPayload } from './sync'
import {
FLUSH_RATE_LIMIT_MS,
enqueueQueryStringUpdate,
getQueuedValue,
scheduleFlushToURL
} from './update-queue'
import { safeParse } from './utils'
Expand Down Expand Up @@ -258,7 +259,11 @@ function parseMap<KeyMap extends UseQueryStatesKeysMap>(
return Object.keys(keyMap).reduce((obj, stateKey) => {
const urlKey = urlKeys?.[stateKey] ?? stateKey
const { defaultValue, parse } = keyMap[stateKey]!
const query = searchParams?.get(urlKey) ?? null
const queuedQuery = getQueuedValue(urlKey)
const query =
queuedQuery === undefined
? (searchParams?.get(urlKey) ?? null)
: queuedQuery
if (cachedQuery && cachedState && cachedQuery[urlKey] === query) {
obj[stateKey as keyof KeyMap] =
cachedState[stateKey] ?? defaultValue ?? null
Expand Down

0 comments on commit c7aafab

Please sign in to comment.