8

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 Answers2

22

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, useEffect } from 'react'
import axios from 'axios'

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

    useEffect(() => {
        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>
    )
}
Anatol
  • 3,720
  • 2
  • 20
  • 40
  • 1
    it works great. Thanks for your time and info. – Farrokh Rostami Kia Dec 20 '20 at 21:42
  • Hi how will you access error object here, if i try to use error.response.status it is giving me undefined – Masood Mar 15 '21 at 08:25
  • Hey Masood. 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: ``` – Farrokh Rostami Kia May 03 '21 at 17:55
  • I'm having troubles using the context in the interceptor file, but with a state string property (e.g. access_token). If I try to get the access_token from my context, it's always null. Using a context method (signIn / signOut), I have no problem... Does anyone know why? – Esteban Chornet May 31 '21 at 06:24
  • why using useMemo and not useEffect? – Syed SaeedulHassan Ali Mar 24 '22 at 11:20
  • @SyedSaeedulHassanAli you can use either in this case – Anatol Mar 26 '22 at 13:55
  • it should definitely be useEffect w/ and it should probably return a function that ejects the interceptor. – misterManager Apr 20 '22 at 20:06
  • @Anatol Just a note according to docs (https://beta.reactjs.org/apis/react/useMemo#parameters) function you pass to `useMemo` should be *pure*. Doing this in effect could be Ok, but then children's effects normally run earlier than parents IMHO. – Giorgi Moniava Sep 16 '22 at 20:41
0

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]);