Issue
I have the following function that makes a GET request for my user information and caches it using react query's fetchQuery so that every call after the first one does not make a GET request and instead just pulls the data from the cache.
export const getSelf = async (): Promise<UserData> =>
await queryClient.fetchQuery(['getSelf'], async () => {
try {
const { data } = await request.get('/users/me');
// @todo: This sideloads a bunch of stuff, that we could cache
return data;
} catch (error) {
throw new Error('Failed to fetch user information');
}
});
The problem is that now I actually want to make a new GET request in order to check if the user data has changed, but calling getSelf()
pulls from the cache. How can I instruct fetchQuery to make a fresh GET request and not used the cache?
Solution
A slight modification to your function will allow you to first invalidate the query (which will remove it from the cache).
export const getSelf = async (skipCache = false) => {
if(skipCache) { queryClient.invalidateQueries(['getSelf']); }
return queryClient.fetchQuery(['getSelf'], async () => {
try {
const { data } = await request.get('/users/me');
// @todo: This sideloads a bunch of stuff, that we could cache
return data;
} catch (error) {
throw new Error('Failed to fetch user information');
}
});
}
Answered By - Chad S.
Answer Checked By - - Marilyn (ReactFix Volunteer)