Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
Logic to refresh token automatically without showing error to our users
*/
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => {
return response;
},
(error: AxiosError) => {
if (
error.response.status === 403 &&
error.response.data.detail.includes("Invalid token header")
) {
return processRefreshToken(error);
} else {
return Promise.reject(error);
}
}
);
function processRefreshToken(error) {
return new Promise((resolve, reject) => {
let retries = 0;
let listener = null;
const oldToken = getToken();
if (!isRefreshingToken) {
dispatchRefreshToken();
isRefreshingToken = true;
}
listener = storeFactory.getStore().subscribe(() => {
retries += 1;
const newToken = getToken();
if (oldToken !== newToken) {
const config = error.config;
setAuthHeader(config);
listener();
isRefreshingToken = false;
resolve(axios.request(error.config));
}
// Unsubscribe fom store and return error
if (retries >= MAX_RETRIES) {
listener();
reject(error);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment