Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/query-persist-client-core-settimeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-persist-client-core': patch
---

Use `setTimeout(..., 0)` instead of `notifyManager.schedule` in `experimental_createQueryPersister` so restored and fetched query state is applied before persisting or running post-restore callbacks, even when a microtask scheduler is configured.
19 changes: 6 additions & 13 deletions packages/query-persist-client-core/src/createPersister.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
hashKey,
matchQuery,
notifyManager,
partialMatchKey,
} from '@tanstack/query-core'
import { hashKey, matchQuery, partialMatchKey } from '@tanstack/query-core'
import type {
Query,
QueryClient,
Expand Down Expand Up @@ -227,10 +222,8 @@ export function experimental_createQueryPersister<TStorageValue = string>({
await storage.removeItem(storageKey)
} else {
if (afterRestoreMacroTask) {
// Just after restoring we want to get fresh data from the server if it's stale
notifyManager.schedule(() =>
afterRestoreMacroTask(persistedQuery),
)
// Wait for the query to apply the restored data before refetching.
setTimeout(() => afterRestoreMacroTask(persistedQuery), 0)
}
// We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves
return persistedQuery.state.data as T
Expand Down Expand Up @@ -341,10 +334,10 @@ export function experimental_createQueryPersister<TStorageValue = string>({
const queryFnResult = await queryFn(ctx)

if (matchesFilter && storage != null) {
// Persist if we have storage defined, we use timeout to get proper state to be persisted
notifyManager.schedule(() => {
// Wait for the query to apply the fetched data before persisting its state.
setTimeout(() => {
persistQuery(query)
})
}, 0)
}

return Promise.resolve(queryFnResult)
Expand Down
Loading