reactjstanstack

TanStack query - Invalidate queries not working with retry


I have a setup using the queryClient's defaultOptions.

The queries are set to always retry up to three times, and the mutations are set to retry on a specific error.

This works in most cases as expected. However, there are cases where a useMutation call is followed by using invalidateQueries on a useQuery get request in order to trigger a refetch. This happens in both cases of the useMutation succeeding or failing.

My issue is, the useQuery call is not retrying on failures in this case when it should be.

  1. the failing mutation call (doesn't retry as expected)

  2. the failing get call triggered by the invalidate queries (doesn't retry, but should be)

I'm struggling to find anything in the documentation about this. Is invalidateQueries not designed to fire retries if it fails? How do I get it to apply the retry it does elsewhere when the useQuery call is fired normally?

The config is:

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 1000,
      retry: 3,
      throwOnError: true,
      refetchOnMount: false,
      refetchOnWindowFocus: false,
    },
    mutations: { retry: () => functionToCheckErrorCode },
  },
})

And the invalidate on error/success is as follows:

queryClient.invalidateQueries({ queryKey: ["getKey"] })

Solution

  • If I understand correctly, invalidateQueries() only marks queries as stale. It triggers a refetch, but retry logic only applies when the refetch is initiated by a component using useQuery. So to ensure that retries happen after invalidation, the component using useQuery(["getKey"]) must still be mounted. If it's unmounted or is not re-rendering, I don't think retries will occur. So I think the solution might be to make sure that the component with useQuery(["getKey"]) is mounted when you call invalidateQueries(), then the retry logic will then apply.