Try refresh token and invalidate query when react-query encounters 401

Viewed 4392

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.

1 Answers

I don't think you can trigger side-effects like tryRefreshToken() or queryClient.invalidateQueries directly in the render function. Try putting these side-effects into the onError callback of useQuery, or in a useEffect. Something like:

function useMyQUery() {
  const queryClient = useQueryClient()
  const { tryRefreshToken } = useSession()

  return useQuery(key, fn, {
    onError: (error) => {
      if (error.status === 401) {
        tryRefreshToken().then((tokenRefreshSucccessful) =>
          queryClient.invalidateQueries("todos")
        )
      }
    }
  })
}
Related