Skip to content

Commit

Permalink
fix(fe): 🐛 refresh api call too much times
Browse files Browse the repository at this point in the history
  • Loading branch information
lehuygiang28 committed Aug 25, 2024
1 parent a5595ca commit ce4620e
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions apps/fe/src/hooks/useAxiosAuth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useSession } from 'next-auth/react';
import { useEffect } from 'react';
import { AxiosRequestConfig } from 'axios';

import { useAxios } from './useAxios';
import { useRefreshToken } from './useRefreshToken';

Expand All @@ -9,6 +11,9 @@ export type UseAxiosAuthPayload =
}
| undefined;

const requestsQueue: AxiosRequestConfig[] = [];
let isRefreshing = false;

export function useAxiosAuth(payload?: UseAxiosAuthPayload) {
const { instance: axiosInstance } = useAxios();
const { data: session, status } = useSession();
Expand Down Expand Up @@ -43,8 +48,27 @@ export function useAxiosAuth(payload?: UseAxiosAuthPayload) {
const prevRequest = error?.config;
if (error?.response?.status === 401 && !prevRequest?.sent) {
prevRequest.sent = true;
await refreshToken();
prevRequest.headers['Authorization'] = `Bearer ${session?.user.accessToken}`;
// Queue the request
requestsQueue.push(prevRequest);
if (!isRefreshing) {
isRefreshing = true;
try {
await refreshToken();

for (const queuedRequest of requestsQueue) {
queuedRequest.headers['Authorization'] =
`Bearer ${session?.user?.accessToken}`;
axiosInstance(queuedRequest);
}

requestsQueue.length = 0; // Clear the queue
} catch (refreshError) {
// Handle refresh token error
console.error('Failed to refresh token:', refreshError);
} finally {
isRefreshing = false;
}
}
return axiosInstance(prevRequest);
}
return Promise.reject(error);
Expand Down

0 comments on commit ce4620e

Please sign in to comment.