[Bug] Persisted query without observers does not respect stale time #9233
Describe the bug#
// experimental_createQueryPersister
const restoredData = await retrieveQuery(
query.queryHash,
(persistedQuery) => {
query.setState({
dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
errorUpdatedAt: persistedQuery.state.errorUpdatedAt
});
if (query.isStale()) {
query.fetch();
}
}
);
// query.js
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
- When restoring a persisted query, a callback is passed, which is called after retrieving the query data.
- The
isStale()method checks if there are observers, and if so, uses their staleness calculation. If there are no observers, it falls back to checkingthis.state.data === undefined || this.state.isInvalidated. - But in a prefetch scenario, when a query is restored from persistence, it may not have observers yet. And neither of the other checks may be true.
- So because
isStaledoes not do a time-based staleness check, it returnsfalsein this check, even when the query should be considered stale when considering itsstaleTime&dataUpdatedAt. - So the stale persisted query is not lazily refetched after restoring <-- bug.
This does not match the behavior described in the docs:
staleTime is also respected after restoring the Query, so if data is considered stale, it will be refetched immediately after restoring.
https://tanstack.com/query/latest/docs/framework/react/plugins/createPersister
To fix: consider time-based staleness:
const restoredData = await retrieveQuery(
query.queryHash,
(persistedQuery) => {
query.setState({
dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
errorUpdatedAt: persistedQuery.state.errorUpdatedAt
});
const resolvedStaleTime = typeof query.options.staleTime === "function"
? query.options.staleTime(query)
: query.options.staleTime;
if (query.isStale() || query.isStaleByTime(resolvedStaleTime)) {
query.fetch();
}
}
);
This works - the only issue is from Typescript, as staleTime is in fact defined on query.options, but not in the QueryOptions type. We don't want to check the staleTime of the observers - as the bug stems from the fact that there might not be any at the point we restore the query.
Your minimal, reproducible example#
N/A
Steps to reproduce#
- Persist query with
staleTime - Prefetch query before observer rendered
- See query restored but not refetched,
staleTimenot respected
Expected behavior#
Prefetched persisted queries should respect staleTime when determining staleness in persist refetch.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
OS: macOS 14.6 Browser: latest chrome
Tanstack Query adapter#
react-query
TanStack Query version#
5.79.0
TypeScript version#
5.8.2
Additional context#
No response
TkDodo closed this
TkDodo added labelsworks as designed
Thanks for your detailed response.
I believe there is an issue. You are correct, my use is in prefetching before observers are mounted:
await client.prefetchQuery(queryOptions)Called during app bootstrap with a
staleTimedefined in a configuration object. This is in effect equivalent to the recommendation of usingfetchQuerywithstaleTime.My call chain is:
prefetchQuery → fetchQuery → [if query.isStaleByTime === true] // query is stale by time → query.fetch → fetchFn → this.options.persister → persisterFn → [if query.isStale() === false] // query is not stale and not refetchedAnd those two stale checks not matching illustrate the problem.
A query can in fact not be stale without an observer
This doesn't seem like it ought to be true, as the call to
query.isStaleByTimeinfetchQueryshows:fetchQuery(options) { ... return query.isStaleByTime( resolveStaleTime(defaultedOptions.staleTime, query) // <---- no observer, but can be stale ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); }...which staleTime should be taken for the query here if you have no observer?
In this case, the
staleTimepassed toprefetchQuery. The issue of requiring an observer to supplystaleTimeseems to narrow too much - shouldn't the concept be instead whatever the caller supplied, whether an observer or a client method?This doesn't seem like it ought to be true
okay, let me rephrase it then. A query doesn’t know if it’s stale or not, because that depends on call sides providing that information. Observers have that information.
fetchQueryandprefetchQueryalso have that information, as they understandstaleTimeand have this added explicitly to their types:The
staleTimeyou pass tofetchQueryis not stored on the Query. AfterfetchQueryis done, thatstaleTimeyou passed is gone. Same goes for observers: they are stored on observers, but as soon as the observer unmounts, the query knows nothing about thestaleTimethis observer had.My call chain is:
Note the two differences in your call chain:
query.isStaleByTimeneeds a time to be passed in, and computes it from therequery.isStale()operates on the query only, with the information it has. That is only mounted observers / data, not previous calls to imperative methods.
Those are great clarifications, as a description of current state. I still do think, as an end user, the current state does not match my expectations of how it should operate - the internals of "what owns
staleTime" should not matter to the consumer. I would expect "staleness" to mean the same thing, with the same effects, regardless of what's doing the calling. But as this seems to be an intentional design decision, I'll note this and move on.Thank you for engaging - your work on this library has been invaluable and I much appreciate it.
thanks, this is one of the limitations that we’re currently have to accept. Maybe we can make the docs better?
FWIW, I tried moving staleTime to the query twice already and couldn’t make it work, and we also got feedback that staleTime on a per-observer basis is a “feature”.
Sign in to join this conversation.
A query can only be stale by time when there are observers, as stale-ness depends on how you look at it. A query can in fact not be stale without an observer - that’s why
query.optionsdoes’t have it.don’t rely on it! It’s only there at runtime if you inspect the options object because we spread all options we pass in instead of removing excess properties, as TypeScript doesn’t mind excess properties. This is not guaranteed behaviour, and also might not have the correct value if you use different staleTimes.
that sentence refers to what we do internally in the persister when using it on
useQuery.looking at this code in isolation:
which
staleTimeshould be taken for the query here if you have no observer? The query has data, and we know when the data was created, but we don’t know when it should be considered stale because without observers, there is nothing that tells us whatstaleTimeshould be. The fact that you seequery.options.staleTimeimplies that you, at some point, had an observer mounted with astaleTimeor maybe usedqueryClient.prefetchQuery()which used one. But again, those are observer specific and not stored on a query, it’s also not persisted to the external storage.What you want instead if likely to use
queryClient.fetchQuery, and pass astaleTimeto it to indicate when you should trigger a refetch: