Question 1: How to navigate to the `/login` route when catching the error in `Axios` interceptors.
=> I am not able to use the useNavigate hook here because of react hooks rules. Here, is my code.
axiosInstance.js
import axios from "axios";
import { useNavigate } from "react-router-dom";
const instance = axios.create();
const navigate = useNavigate();
instance.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Error handling code
instance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response.status === 401) {
navigate("/login");
}
return Promise.reject(error);
}
);
export default instance;
services.js
export const GetData = async () => {
return await axiosInstance.get(`${window.env.REACT_APP_API_URL}/getData`);
};
export const GetDashboardData = async () => {
return await axiosInstance.get(`${window.env.REACT_APP_API_URL}/dashboard`);
};
.... More API services here...
Component.js
useEffect(() => {
const fetchData = async () => {
await GetData()
.then((res) => {
console.log(res.data);
})
.catch((error) => {
console.log(error);
});
};
fetchData();
}, []);
=> After checking various articles, I have found out that - We should implement interceptors globally in ReactJS, and load it on the first render (Reference: https://jskim1991.medium.com/react-routing-to-an-error-page-with-axios-interceptors-f4dcb5f00a3c)
=> My Question is, How to use the useNavigate hook in interceptor and Is it a good practice to add it in App.js file and render only once ?
Question 2: How can interceptors be implemented to handle different tokens for various user roles?
In my web application, I have various user roles such as admin, regular user, and super admin, each with their respective access tokens stored in the local storage as follows:
Admin token: stored with the key "adminToken"
User token: stored with the key "token"
Super admin token: stored with the key "superToken"
If I add a global interceptor to attach an Authorization header to each request, how will the interceptor differentiate between API requests meant for admin access (requiring the admin token) and those for regular user access (requiring the user token) and similar cases with superToken?
I believe there should be a method to integrate multiple interceptors, but I haven't been able to find any solutions for this issue. Any help on this matter would be greatly appreciated.