I want to redirect to '/login'
in axios interceptor while handling error.
My code:
import axios from "axios";
import { redirect } from "react-router-dom";
export const instance = axios.create()
instance.interceptors.request.use(
... other code
);
instance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const originalRequest = error.config;
console.log(error?.response.data)
console.log(originalRequest._retry)
if (
error.response.status === 401 &&
originalRequest.url === "http://0.0.0.0:8000/auth/refresh-token"
) {
localStorage.removeItem("refresh_token");
localStorage.removeItem("access_token");
// I tried this
return redirect("/login")
// And also I tried this
//router.navigate("/login");
return Promise.reject(error);
}
if (error.response.status === 401 && !originalRequest._retry) {
... other code
}
return Promise.reject(error);
}
);
I’ve tried two ways to do this:
- First:
return redirect
- Second:
router.navigate
But nothing works.
This how I defined router:
export const router = createBrowserRouter([
{ path: "*", Component: Root },
]);
2
Answers
I used to implement React routing using useNavigate() in react-router-dom. You can refer below.
The
redirect
utility only works inRoute
component’s loaders/actions. I suggest importing theaxios
instance so the interceptors can be instantiated in scope with theuseNavigate
hook using auseEffect
hook. If you like, the logic can be abstracted into a custom hook.Example:
Use the
useAxiosInterceptors
hook in your route protection component.