Do not use stale cached data on mount of fresh observer #5695
Replies: 2 comments 3 replies
-
There are multiple ways to handle this:
you can refetch right away if you want, either by using
If you don't want to fetch right away, you can check for |
Beta Was this translation helpful? Give feedback.
-
@TkDodo is there a suspense compatible solution? I'm handling a similar scenario and this is the code I've got so far, but I still need to add some extra tests: if (queryOptions.suspense && enabled) {
if ((!isFetchedAfterMount && isStale) || isLoading) {
const observer = new QueryObserver(queryClient, { queryKey: queryOptions.queryKey })
throw observer.fetchOptimistic(queryOptions)
}
} P.S.: My code might be slightly more complex because an additional thing we are trying to add is the ability to turn |
Beta Was this translation helpful? Give feedback.
-
Hi, apologies if this has been asked before (searched but did not find). Is there a way to configure useQuery to use cache data on mount only if that data is not stale? Consider this scenario:
A modal is launched which makes use of a query. There's no initialData, so the screen shows a loading spinner (isLoading) until the data is fetched.
The modal is then closed. The query is now
inactive
.Another process mutates related data, and invalidates that query. The cache data is now stale, but is not refetched because the query has no active observers.
The modal is opened again, moving the query state to
stale
. It displays the stale cached data momentarily until it has refetched at which point the new data is displayed.Ideally in this scenario we'd show a loading spinner again, but only if the cache data is stale. If the cached data is not stale, we'd like to use it. For example if you open the modal, close it, then open it immediately again, it should be able to use the cache and not fetch anything. But if you close the modal, mutate, then open it again, it should refetch and never display the stale data.
Is this configuration possible? One approach would be to clear the cache via removeQueries as opposed to invalidating it, but that requires the mutation having knowledge of how the query is used, and determining whether to invalidate or remove may be dynamic/contextual based on the application state (which ideally the mutation wouldn't have to consider).
Beta Was this translation helpful? Give feedback.
All reactions