I have setup for axios and react-query together for my food application . I want to implement refreshing token only once for more than 2 parallel request and retry all the pending failed request . I searched so many solutions on the web , tried them but none of them worked . Here is my code reference .
let isRefreshing = false;
let failedQueue = [];
async function refreshToken() {
const response = await normalRoute.post("/users/refresh");
return response.data.accessToken;
}
privateRoute.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response.status === 401) {
failedQueue.push(error.config);
if (!isRefreshing) {
isRefreshing = true;
const token = await refreshToken();
store.dispatch(setAccessToken(token));
const promsieArray = failedQueue.map((config) => {
config.headers.authorization = `Bearer ${token}`;
return privateRoute(config);
});
failedQueue = [];
return Promise.resolve(promsieArray);
}
}
}
);
2
Answers
Thankyou I found solution ..
I think your solution is a little too complicated. I’d simply store the Promise returned by
refreshToken()
untill it is fulfilled and let all incoming401
s await the same Promise, then retrying.And kill that Promise when it is fulfilled so that later
401
s have a chance to refresh the token yet again.