Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use hooks in react-query onError handler?

We are using Next.js with react-query everywhere. What we want to do is to have a global query setup that when a call to an endpoint fails because the access token expired, it refreshes the token and re-runs the query.

The error mode should be that the user gets redirected to login. We have come a long way with using react-query's built in onError and retry settings.

With a custom function we can refresh the token and then retry the original request again. However, after trying again, we would want to redirect the user to the login page. For this we need useRouter from Next which is a hook. useQuery in react-query is also a hook.

Is there a way to combine these two, so that we can use the router inside the onError of QueryClient? Or is this completely the wrong way to go about it?

What we are trying is something like this:

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      onError: () => router.push('/login'),
    }
  }
})

Is this even possible?

like image 733
Imre_G Avatar asked Jun 12 '26 14:06

Imre_G


1 Answers

You can import your router instance directly then use it to configure the query client.

import Router from 'next/router'
// ...

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      onError: () => Router.push('/login'),
    }
  }
})

This is discussed here: Using next/router outside of components

like image 102
Chad S. Avatar answered Jun 14 '26 13:06

Chad S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!