useContext inside axios interceptor

Viewed 5442

I cant figure out why my useContext is not being called in this function:

import { useContext } from "react";
import { MyContext } from "../contexts/MyContext.js";
import axios from "axios";

const baseURL = "...";

const axiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
.
.
.
});
axiosInstance.interceptors.response.use(
  (response) => response,
  async (error) => {
    const { setUser } = useContext(MyContext);
    console.log("anything after this line is not running!!!!");
    setUser(null)

.
.
. 

My goal is to use an interceptor to check if the token is live and if its not clear the user and do the login. I'm using the same context in my other react components. And its working fine there, its just not running here! any idea whats I'm doing wrong?

2 Answers

I had the same issue as you. Here is how I solved it:

You can only use useContext inside a functional component which is why you can't execute setUser inside your axios interceptors.

What you can do though is to create a separate file called WithAxios:

// WithAxios.js

import { useContext, useMemo } from 'react'
import axios from 'axios'

const WithAxios = ({ children }) => {
    const { setUser } = useContext(MyContext);

    useMemo(() => {
        axios.interceptors.response.use(response => response, async (error) => {
            setUser(null)
        })
    }, [setUser])

    return children
}

export default WithAxios

And then add WithAxios after MyContext.Provider to get access to your context like this for example:

// App.js

const App = () => {
    const [user, setUser] = useState(initialState)

    return (
        <MyContext.Provider value={{ setUser }}>
            <WithAxios>
                {/* render the rest of your components here  */}
            </WithAxios>
        </MyContext.Provider>
    )
}

I don't have any issues catching the errors in this schema. are you catching them in the axios interceptor? here how I modified it:

useMemo(() => {
    axiosInstance.interceptors.response.use(
      (response) => response,
      async (error) => {
        const originalRequest = error.config;

        // Prevent infinite loops
        if (
          error.response.status === 401 &&
          originalRequest.url === // your auth url ***
        ) {
          handleLogout();
          return Promise.reject(error);
        }

        if (
          error.response.status === 401 &&
          error.response.data.detail === "Token is invalid or expired"
        ) {
          handleLogout(); // a function to handle logout (house keeping ... ) 
          return Promise.reject(error);
        }
        if (
          error.response.data.code === "token_not_valid" &&
          error.response.status === 401 &&
          error.response.statusText === "Unauthorized"
        ) {
          const refreshToken = // get the refresh token from where you store

          if (refreshToken && refreshToken !== "undefined") {
            const tokenParts = JSON.parse(atob(refreshToken.split(".")[1]));

            // exp date in token is expressed in seconds, while now() returns milliseconds:
            const now = Math.ceil(Date.now() / 1000);

            if (tokenParts.exp > now) {
              try {
                const response = await axiosInstance.post(
                  "***your auth url****",
                  {
//your refresh parameters
                    refresh: refreshToken,
                  }
                );
                
// some internal stuff here ***

                return axiosInstance(originalRequest);
              } catch (err) {
                console.log(err);
                handleLogout();
              }
            } else {
              console.log("Refresh token is expired", tokenParts.exp, now);
              handleLogout();
            }
          } else {
            console.log("Refresh token not available.");
            handleLogout();
          }
        }

        // specific error handling done elsewhere
        return Promise.reject(error);
      }
    );
  }, [setUser]);

Related