React Query invalidateQueries does not set loading to true

Viewed 3388

I'm using the useMutation hook to delete the entity and the useQuery hook to load the entities from the api as follows:

const { mutate: $delete } = useMutation(deleteDiscipline, {
  onSuccess: () => {
    queryClient.invalidateQueries('disciplines')
  },
})

const { isLoading, data: disciplines } = useQuery(['disciplines', filter], getFilteredDisciplines)

I rely on the isLoading field to display the loading status bar. It works when I trigger refetch by switching tabs or changing the filter (query depends on filter state). But when I call queryClient.invalidateQueries the api call is made and data is updated, but the isLoading field stays true for the entire refetching time.

Awaiting for the invalidation didn't help either:

const { mutate: $delete } = useMutation(deleteDiscipline, {
  onSuccess: async () => {
    await queryClient.invalidateQueries('disciplines')
  },
})

How can I detect the request occurs (including all the triggers like query invalidations and others that I haven't encounter yet)?

2 Answers

isLoading is only true for a hard-loading state, where you have no data to display. Since react-query embraces stale-while-revaliate, it will give you stale data while at the same time doing a background refetch. So your status in that case is still success, with isSuccess being true, and data being available.

isFetching is an additional flag that is always true when a request is in-flight. This is true for the first loading as well as for all background updates.

The solution was to use the isFetching field instead of the isLoading for subsequent fetches.

Related