Reputation: 227
In my solution, I am wrapping React Query's useQuery
hook with my own to have a specific retry logic:
export function useMyQuery(key, queryFn, options = {}) {
const queryClient = useQueryClient();
const query = useReactQuery(key, queryFn, {
...options,
retry: async(count, error) => await retry(count, error, queryClient),
});
return query;
}
The retry
function itself is as follows:
export async function retry(count, error, queryClient) {
if (error?.statusCode === 401) {
// caught 401, trying to refresh token;
if (await refreshToken(queryClient)) {
queryClient.refetchQueries('fetchSession');
return true;
}
}
// Retry 3 times
return count < 3;
}
and, finally my fetchSession
query looks like this:
const { data } = useQuery('fetchSession', () => {
console.log('fetching new session...');
return Auth.currentSession();
})
My Goal is to trigger refetch of the "fetchSession" query after I have successfully refreshed the token in the code above, however, the query is never refetched i.e. the query body is never run after the token is refreshed. Besides using refetchQueries
method on queryClient
, I have also tried invalidateQueries
to no effect.
Upvotes: 1
Views: 2507
Reputation: 29056
The retry
function is not async - it expects you to return a boolean
, not a Promise<boolean>
, so that doesn't work.
I would do this logic either with an axios interceptor (if you are using that), or just in your queryFn:
useQuery('fetchSession', async () => {
try {
const { data } = await axios.get(...)
return data
} catch(error) {
if (error.statuscode === 401) {
const token = await refreshToken(queryClient))
const { data } = await axios.get(...) // pass token here? don't know how this works for you :)
return data
} else {
throw error
}
}
})
Upvotes: 1