I have a custom hook which I have attached an axios interceptor to check if my token is expired. The problem is that it causes an infinite loop on any component I attach it to. I am using this hook on every request that needs authentication. i don't understand why there is an infinite loop. Any help? Here is my code
import { axiosPrivate } from "../axios";
import useAuth from "./useAuth";
import jwtDecode from "jwt-decode";
import useRefresh from "./useRefresh";
import { useEffect } from "react";
//run before any requests
const useAxiosPrivate = () => {
const refresh = useRefresh();
const { auth } = useAuth();
console.log("infinite loop")
//my useeffect
useEffect(() => {
axiosPrivate.interceptors.request.use(
async (config) => {
let currentDate = new Date();
if (auth?.accessToken) {
const decodedToken = jwtDecode(auth.accessToken);
if (decodedToken.exp * 1000 < currentDate.getTime()) {
const data = await refresh();
console.log("called")//logs only when the token is expired else doesn't log
config.headers["authorization"] = "Bearer " + data.accessToken;
}
}
return config;
},
//cleanup function
(error) => {
return Promise.reject(error);
},
);
}, [refresh, auth]);
return axiosPrivate;
};
export default useAxiosPrivate;