In ReactJS project, I setup a global Axios interceptor to handle 401 error and redirect to the login page. This is working as expected if the server returns 401 error.
//global interceptor for handling 401 (invalid token) response.
axios.interceptors.response.use(
function (response) {
console.log("Axios defaut interceptor");
return response;
},
function (error) {
if (401 === error.response.status) {
alert(
"Your session has expired. You will be redirected to the login page."
);
window.location = "/login";
} else {
return Promise.reject(error);
}
}
);
The problem is that multiple GET requests are sent from the main page Class component's constructor() method. This causes the alert message to be shown multiple times.
What is the best way to handle the error and redirect to the login page only once?