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?
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 executesetUser
inside your axios interceptors.What you can do though is to create a separate file called
AxiosErrorHandler
:And then add
WithAxios
afterMyContext.Provider
to get access to your context like this for example: