fetchQuery
returns stale data when used with createPersister
#8075
Labels
fetchQuery
returns stale data when used with createPersister
#8075
Describe the bug
I noticed that when using
createPersister
and then callingqueryClient.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 likequeryClient.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, callingfetchQuery
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, asfetchQuery
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).Your minimal, reproducible example
https://codesandbox.io/p/sandbox/loving-brook-9ln67f
Steps to reproduce
fetchQuery
, and the counter data is also persisted tolocalStorage
usingcreatePersister
.queryClient.clear()
fetchQuery
is returning the stale data fromcreatePersister
, even though thestaleTime
is set to 10ms.fetchQuery
now 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 text was updated successfully, but these errors were encountered: