`fetchQuery` returns stale data when used with `createPersister` #8075
Describe the bug#
I noticed that when using createPersister and then calling queryClient.fetchQuery, it will always return stale data from the persisted cache (if there's no data in the local cache).
Taking a look at the createPersister code, I can see that it signals if the query is stale, but it still returns the stale data. While this makes sense in a useQuery context, it doesn't make sense when using a procedural function like queryClient.fetchQuery, where we expect it to fetch the latest data if the cache is stale.
This makes it difficult to use the persister in a non-React context, e.g. in an extension service worker, where we might want to make procedural calls to fetchQuery to update some data in the background. I'm using a very questionable hack right now to get around this, calling fetchQuery two times. The first time, it returns the stale persisted data and loads it into the local cache. The second time, it actually runs the query function, as fetchQuery now detects stale data in the local cache. This has the desired effect of fetching the latest data, and automatically saving it to the persister (indexedDB in my case).
const staleData = await queryClient.fetchQuery(...)
await new Promise((r) => setTimeout(r, 100)); // this is necessary because the local cache isn't loaded immediately
const freshData = await queryClient.fetchQuery(...)
Your minimal, reproducible example#
https://codesandbox.io/p/sandbox/loving-brook-9ln67f
Steps to reproduce#
- Click on the "Fetch query" button a couple times. The counter will advance, as expected. The button is calling
fetchQuery, and the counter data is also persisted tolocalStorageusingcreatePersister. - Click on "Clear local cache," which will clear React Query's local cache using
queryClient.clear() - Click "Fetch query" again. This time the counter will not advance, as
fetchQueryis returning the stale data fromcreatePersister, even though thestaleTimeis set to 10ms. - If you click "Fetch query" one more time, this time the counter will advance, as
fetchQuerynow detects stale data in the local cache.
Expected behavior#
I expect fetchQuery to run the query function and return the latest data, if it sees that the data from the persister is stale.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
macOS, Chrome 128
Tanstack Query adapter#
react-query
TanStack Query version#
v5.56.2
TypeScript version#
v5.6.2
Additional context#
This is tangentially related to the discussions in #6310 and #7677
The way the persister is implemented is that it returns cached data from the persister, and triggers a background refetch if the restored data has been considered stale:
as you can see, the fetch is now awaited. @DamianOsipiuk do you think it makes sense to await this fetch in some situations and return the fresh data? Maybe with a new option on the persister?
TkDodo added labelspackage: query-persist-client-core
TkDodo added labelsexperimental
Yeah. I think in the spirit of SWR we should keep current behaviour as default. But we can definietly add an option to wait for fresh data when persisted data is stale.
awaitWhenStaleor something similar.we should consolidate naming a bit. On
ensureQueryData, we haverevalidateIfStale: boolean. I’m not super happy with different namings, so I might want to re-think this a bit for a v6.It looks like I'm able to work around this using the new
persister.persisterRestoreAll()function. Here is the new code that fixes the issue based on my original example above.Basically, if you're using the persister and you want to work directly with the queryClient to call
queryClient.fetchQuery(),queryClient.ensureQueryData(), etc. (e.g. loading/updating data in the background, outside of React) you need to first manually load the React Query cache from the persister into the queryClient. Runningawait persister.persisterRestoreAll(queryClient)will do exactly this. Then, all the queryClient functions should behave how you'd expect, either using the restored cache immediately, or running thequeryFnif the restored cache data is stale.I know this is still an experimental feature, but I think it was helpful for me to think of the persister as something quite separate from React Query - that is, an external storage that React Query doesn't really know anything about. Within a React component, the persister will lazily auto-restore and inject the cache as needed. However, if you're working with the queryClient imperatively / outside of React, the cache needs to be manually restored from the persister first.
fa-sharp(GitHub profile, opens in a new tab) closed this
fa-sharp(GitHub profile, opens in a new tab) reopened this
Keeping this issue open for now, as I see there might be some open questions on naming, or adding an option to the
ensureQueryDatafunctionthis will happen as part of:
TkDodo closed this
I searched for this issue 2 hours until if saw that
if (afterRestoreMacroTask) { // Just after restoring we want to get fresh data from the server if it's stale notifyManager.schedule(() => afterRestoreMacroTask(persistedQuery), ) } // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves return persistedQuery.state.data as TAnd this is used in fetchQuery, why the heck?
I did this workaround for now:
// Load the data into cache first and then fetchData to avoid stale data await persister?.restoreQuery(queryClient, snapshotStashQueryOptions.queryKey) stashItems = await queryClient.fetchQuery({ ...snapshotStashQueryOptions, persister: undefined, staleTime: SNAPSHOT_STASH_STALE_TIME_MS, gcTime: SNAPSHOT_STASH_STALE_TIME_MS }) // Since I don't have entries defined in localForage restoreQuery: async (queryClient: QueryClient, queryKey: QueryKey) => { if (!queryStorage) return const queryHash = hashKey(queryKey) const storageKey = `${QUERY_PERSISTER_KEY_PREFIX}-${queryHash}` const value = await queryStorage.getItem(storageKey) if (!value) return let persistedQuery: PersistedQuery try { persistedQuery = await deserialize(value) } catch { await queryStorage.removeItem(storageKey) return } if (isExpiredOrBusted(persistedQuery)) { await queryStorage.removeItem(storageKey) return } queryClient.setQueryData(persistedQuery.queryKey, persistedQuery.state.data, { updatedAt: persistedQuery.state.dataUpdatedAt }) }
Sign in to join this conversation.
I also experience this issue with ensureQueryData and revalidateIfStale set to true. It doesn't revalidate on page load.