T
TanStack3y ago
rare-sapphire

Only fetch on "initial" load

I'd like to know what is the best approach to initially fetch data every time the app "starts" (so whenever the user either visits or refreshes the app). I'm using PersistQueryClientProvider to cache data to local storage, so in case the initial new fetch fails, I still have a back-up. I've added cacheTime: Infinity and staleTime: Infinity to the UseQueryOptions of the specific fetch, however, now it only initially fetches once and then never again. Thus I feel I have to invalidate the query (make it stale) whenever the app closes or perhaps when it initially loads. Not sure what is the best approach here.
6 Replies
harsh-harlequin
harsh-harlequin3y ago
can you use the enabled property for controlling that?
sensitive-blue
sensitive-blue3y ago
staleTime: Infinity seems right if that's what you want. PersistQueryClientProvider has an onSuccess callback, you can do: queryClient.invalidateQueries() to just refetch everything on-screen after restoring from local storage
rare-sapphire
rare-sapphireOP3y ago
The onSuccess callback is certainly possible. However, for this specific fetch it is preferable to initially disregard the cache and wait for the fetch to finish. The cached version is really something I'd only like to use as a last resort. So therefore I'm actually trying to find a way to invalidate this specific query before it uses the cache...
sensitive-blue
sensitive-blue3y ago
Yeah we'd need to change semantics a bit: onSuccess needs to be able to return a promise and we'd need to await it. Then, you can use onSuccess to invalidate and check for useIsRestoring() to show a spinner if you don't want to see cached data... Not really what persisters are for though. Data stored there is not "fallback" data but valid data that was fetched earlier and thus might be stale
conscious-sapphire
conscious-sapphire3y ago
Maybe you could look into adding a service worker to your project? that way you can let the fetch go through, but with the response, if valid you cache it, if invalid you pull from existing cache. And then react-query is just working over 1 user session.
sensitive-blue
sensitive-blue3y ago
That's a pretty good idea

Did you find this page helpful?