0

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;
louis
  • 422
  • 1
  • 4
  • 14

1 Answers1

0

One of the variables [refresh, auth] is being updated during the execution of useEffect() it should probably be this refresh.

Exemple:

  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1)
  },[count]);

try to map the life cycle of these variables

  • refresh here is only executed when a token is found to be expired. This will call another custom hook to refresh the expired token. The refresh hook seems to work fine – louis Aug 19 '22 at 19:12