How to globally handle error for all react queries at once and refetch?
Asked Answered
U

1

8

I would like to handle, for example, expired access token error for all queries that currently running in my react app.

  1. I need to catch expired access token error globaly
  2. cancel other queries which soon will throw same error
  3. Update access token in context
  4. Invalidate all failed/canceled queries and refetch with new access token.

Is there a way to do it provided by React Query? Could you show simple example how to achieve that?

Unanimity answered 28/3, 2023 at 18:12 Comment(3)
Create a Wrapper over useQuery and handle your custom logic there.Gayegayel
@RohitKhanna I need to handle errors globally for whole app, not only for one useQuery hookHuzzah
Especially when I use useQueries so several queries are running simultaneously and new access token has to be synchronisedHuzzah
I
20

React Query has global event handlers on the level of the QueryCache and MutationCache, that are created with your QueryClient:

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onSuccess,
    onError,
  }),
  mutationCache: new MutationCache({
    onSuccess,
    onError,
  })
})

those event handlers will be called once per query / mutation, for each query / mutation.

see also:

Isomagnetic answered 3/4, 2023 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.