useAxiosInterceptor.ts 724 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { useEffect } from "react";
import { NavigateFunction, useLocation } from "react-router-dom";
import customAxios from "./axios.config";

export const useAxiosInterceptor = (navigate: NavigateFunction) => {
  const location = useLocation();

  useEffect(() => {
    const responseInterceptor = customAxios.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response.status === 401) {
          navigate("/login", {
            replace: true,
            state: { from: location.pathname },
          });
        }
        return Promise.reject(error);
      }
    );

    return () => {
      customAxios.interceptors.response.eject(responseInterceptor);
    };
  }, []);
};