Reputation: 4714
I've configured react-query with infinite stale time, per docs, like this:
<ReactQueryConfigProvider config={{
queries: {
staleTime: Infinity
}
}}>
Most of my queries appropriately never go stale, except one, my 'profile' query:
const getProfile = async () => {
if (!isAuthenticated()) {
return null;
}
try {
const response = await axios.get('/user/profile');
return response.data;
}
catch (error) {
errorCheck(error);
}
};
export const useProfile = () =>
useQuery('profile', getProfile);
This is the query that holds the current user's profile. isAuthenticated()
is a synchronous call that checks to see if we have a user token (so I don't make API calls that I know will fail).
For some reason, in the react-query devtools window, this query shows as stale immediately. I really don't see what I'm doing differently with this one. Any suggestions for debugging this?
Upvotes: 6
Views: 14615
Reputation: 4714
Here's what I think the issue was, and how I solved it.
Because I set staleTime: Infinity
in my ReactQueryConfigProider
, I expected all of my queries to never go stale.
What's different about this query is I invalidate it when something not driven by the UI happens.
I have a session timer in my code that, when the session expired, calls queryCache.invalidateQueries('profile')
to trigger any UI displaying the profile to re-render.
It appears that if invalidateQueries
is ever called outside the context of a query, the settings in ReactQueryConfigProider
are not observed, so staleTime
is set to the default, 0.
To resolve this, for the queries I need to invalidate on a timer, I added { staletime: Infinity }
to the query explicitly:
export const useProfile = () => {
const { data: session } = useSession();
const userId = session?.userId;
return useQuery(['profile', userId], getProfile, { staleTime: Infinity });
};
I won't go so far as to say this is a bug in react-query, but this seems to be a workaround.
Upvotes: 2
Reputation: 11
I ran into the same problem, and it was caused by a component that had a child component which used react-query. Check your component tree and make sure nothing uses useProfile() outside of <ReactQueryConfigProvider>
.
Upvotes: 1