I don't want my components to always refetch when they will mount and already have the query in the cache, so I did:
export const App = ({ props }) => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
refetchOnMount: false,
},
},
})
return (<QueryClientProvider client={queryClient}>{...restOfMyApp}</QueryClientProvider>)
}
When I save some config I tried to invalidate my query with the first key and with that queryClient.invalidateQueries(). In the React-Query devtools, it did show that the query is invalidated, but it just keeps the same results and don't refetch the query.
How can I invalidate the query to be refetched, but don't have to launch the query everytime the component mounts?
Thank you for your help!
if your query is active, it should refetch with invalidateQueries. If its not active, as others have mentioned, set refetchInactive: true.
How can I invalidate the query to be refetched, but don't have to launch the query everytime the component mounts?
Often, caching is better described with a time-based approach, so the better solution to turning off the flags would be to set a staleTime to define how long your data is going to be valid, rather than to define certain points where you want / do not want a refetch.
if you set the staleTime for your query to, say, 20 minutes, none of the refetch events (onMount, onWindowFocus, onReconnect) will trigger a refetch in that time frame. invalidating it manually will still refetch it.
This would also be in-line with how HTTP caching works (think: Cache-Control: max-age=60)
to represent: fetch once, then never again (unless garbage collected), set staleTime: Infinity.
It sounds like there's a bug in your code; could you show how you're invalidating the cache, and your cache keys?
Using refetchInactive should definitely solve the issue for you (emphasis mine):
When set to
true, queries that match the refetch predicate and are not being rendered via useQuery and friends will be both marked as invalid and also refetched in the background
Here's a quick demo on stackblitz.
const client = useQueryClient();
client.invalidateQueries(YOUR_CACHE_KEY, { refetchInactive: true });