diff --git a/.changeset/query-persist-client-core-settimeout.md b/.changeset/query-persist-client-core-settimeout.md new file mode 100644 index 00000000000..47fa401ce8b --- /dev/null +++ b/.changeset/query-persist-client-core-settimeout.md @@ -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. diff --git a/packages/query-persist-client-core/src/createPersister.ts b/packages/query-persist-client-core/src/createPersister.ts index 79943728e79..22044d3f14c 100644 --- a/packages/query-persist-client-core/src/createPersister.ts +++ b/packages/query-persist-client-core/src/createPersister.ts @@ -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, @@ -227,10 +222,8 @@ export function experimental_createQueryPersister({ 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 @@ -341,10 +334,10 @@ export function experimental_createQueryPersister({ 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)