Search code examples
reactjsreact-queryinvalidationtanstackreact-query

Invalidate all queries but refetch only active


I want to achieve the behavior where after successful mutation, all queries with dependent data should be marked as invalid but only active should be refetched right away, and inactive should be refetched only whether they would become active.

As I understand the react-query API, this behavior can be achieved using

queryClient.invalidateQueries(['query-key'], { refetchType: 'active' })

as it invalidates all queries that match but refetch only active ones, but this is not refetch invalid inactive data when it becomes active. Maybe it can be a problem not only in the way invalidation is called but also in some default query options.

Currently, I'm simply refetch all invalid queries, whether they are active or not, but this is quite not the right approach.

// query client defaults
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
      refetchOnMount: false,
      refetchOnReconnect: false,
      refetchOnWindowFocus: false,
    },
  },
})

// mutation with query invalidation
const useCreateExample = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: createExample,
    onSuccess: () => {
      queryClient.invalidateQueries(['example'], { refetchType: 'all' })
    },
  })
}

Solution

  • TLDR: Check your default query options, they can prevent refetching stale data.


    As I predicted, the problem was not in invalidation, but in default query options. As pointed out in Important defaults, stale data will be refetching after some triggers (mounting, refocus, reconnect) by default, but you can prevent this behavior. My defaults prevent data refetching in any case because there was no need for the UI to be updated regularly.

    But it was unclear that even if you invalidate the data from an inactive query and have refetchOnMount: false - the invalid data won't be refetched anyway. Thanks this comment by @tkdodo for the help.