Last active
November 20, 2024 10:00
-
-
Save Tholkappiar/7ee90b3fa50c47f94e126b65bfa5db4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from "react"; | |
import useAuth from "./useAuth"; | |
import useRefreshToken from "./useRefreshToken"; | |
import { axiosPrivate } from "../utils/axiosInstance"; | |
const useAxiosPrivate = () => { | |
const { user } = useAuth(); // context - which contains the JWT Token | |
const refresh = useRefreshToken(); // this hook hits the refresh token endpoint and returns the new access token | |
useEffect(() => { | |
const requestIntercept = axiosPrivate.interceptors.request.use( | |
(config) => { | |
if (!config.headers["Authorization"]) { | |
config.headers["Authorization"] = `Bearer ${user?.token}`; | |
} | |
return config; | |
}, | |
(error) => Promise.reject(error) | |
); | |
const responseIntercept = axiosPrivate.interceptors.response.use( | |
(response) => response, | |
async (error) => { | |
const prevRequest = error?.config; | |
if (error?.response?.status === 401 && !prevRequest?.sent) { | |
prevRequest.sent = true; | |
const newAccessToken = await refresh(); | |
prevRequest.headers[ | |
"Authorization" | |
] = `Bearer ${newAccessToken}`; | |
return axiosPrivate(prevRequest); | |
} | |
return Promise.reject(error); | |
} | |
); | |
return () => { | |
axiosPrivate.interceptors.request.eject(requestIntercept); | |
axiosPrivate.interceptors.response.eject(responseIntercept); | |
}; | |
}, [user, refresh]); | |
return axiosPrivate; | |
}; | |
export default useAxiosPrivate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment