Search code examples
reactjsaxiosuse-context

useContext inside axios interceptor


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?


Solution

  • 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 AxiosErrorHandler:

    // AxiosErrorHandler.js
    
    import { useContext, useEffect } from 'react'
    import axios from 'axios'
    
    const AxiosErrorHandler = ({ children }) => {
        const { setUser } = useContext(MyContext);
    
        useEffect(() => {
            const responseInterceptor = axios.interceptors.response.use(response => response, async (error) => {
                setUser(null)
            })
    
            return () => {
                axios.interceptors.response.eject(responseInterceptor);
            }
        }, [setUser])
    
        return children
    }
    
    export default AxiosErrorHandler
    
    

    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 }}>
                <AxiosErrorHandler>
                    {/* render the rest of your components here  */}
                </AxiosErrorHandler>
            </MyContext.Provider>
        )
    }