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: {
one rror: () => router.push('/login'),
}
}
})
Is this even possible?
CodePudding user response:
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: {
one rror: () => Router.push('/login'),
}
}
})
This is discussed here: Using next/router outside of components