I have this interceptors that logs the user out if unauthorized. I do, however, get more than a 401 response, and the interceptors does therefore run for as many times as the responses I get (4). Is there a way to make it run only for the first one?
This is my code:
api.interceptors.response.use(
(response) => response,
(err) => {
if (err.response.status === 401 && isLoggedIn) {
api
.delete("auth/sign_out")
.then((resp) => {
clearLocalStorage();
})
.catch((err) => {
clearLocalStorage();
});
} else {
return Promise.reject(err);
}
return err;
}
);
You might want something like this to "lock out" the possible re-entrant calls:
let isLoggingOut = false; // global
// ...
api.interceptors.response.use(
(response) => response,
async (err) => {
if (err.response.status === 401 && isLoggedIn) {
if(!isLoggingOut) {
isLoggingOut = true; // disallow re-entrant calls
try {
await api.delete('auth/sign_out');
} catch (deletionError) {
// throw errors away
} finally {
clearLocalStorage();
isLoggingOut = false;
isLoggedIn = false; // if the variable is assignable
}
}
}
return err;
},
);