I would like to create a wrapper hook around react-query's useQuery
hook so that I could catch a 401 error, attempt to refresh access token and if successfully refreshed - invalidate the original query.
Full example of what I am trying to do is here: https://codesandbox.io/s/agitated-booth-hbe12?file=/src/App.js
function useMyQUery() {
const queryClient = useQueryClient();
const { tryRefreshToken } = useSession();
const query = useQuery(...arguments);
if (query.isError && query.error?.status === 401) {
tryRefreshToken().then((tokenRefreshSucccessful) =>
queryClient.invalidateQueries("todos")
);
} else {
return query;
}
return {};
}
In the example I have linked above I am able to catch the error, trigger the function tryRefetchToken
, but the functions inside the useSession
hook do not seem to pick up the token once it is set.
onError
does not suppress the error from being exposed to the consumer, but what works isretry
option, which accepts a callback function (retryCount, error) => ... , which works as expected and does not expose the error to the consumer unless you returnfalse
from that callback. Now the final issue that I have is that queryFn which is set up in the useSession context should read a state valuetoken
from that context, but it never gets the updated value, just the initial one. – Ritual