Why is this react function returning error?

Viewed 32

I am using reactjs, nodejs and axios to create a basic blog app. In my codes, I have these two functions. One is called AutoRefreshToken while the second is a useContext hook. The AutoRefresh function calls my node api to generate a new jwt access token. While the other function is where the AutoRefresh function is called using useEffect.

This is AutoRefreshToken

 const AutoRefreshToken =() => {
 const {setAuth, auth} = useContext(AuthContext);

  const refresh = async () =>{
    try{
         const response = await axios.post("/refresh", {
             withCredentials: true
         });
         console.log(response.data)
         setAuth(response.data);
   

    }catch(err){
        console.log(err)
    }
   
}
 return refresh
}

export default AutoRefreshToken

The useContext code

 import AutoRefreshToken from '../hooks/AutoRefreshToken';

export const AuthContext = createContext({});

export const AuthProvider = ({children})=>{
const [auth, setAuth] = useState({});
const refresh = AutoRefreshToken()


useEffect( async () =>{
   console.log(!auth.user)
        try{
             if(!auth.user){
                await refresh()
             }
           
             
        }
        catch(err){
            console.log(err);
        }
}, [])
return(
    <AuthContext.Provider value={{auth, setAuth}}>
        {children}
    </AuthContext.Provider>
)
};

In the useContext code, I have a state called auth which I use setAuth to set the state. The problem is in the useContext code, setAuth gets an error when it AutoRefreshToken function wants to set the state. The error is

TypeError: setAuth is not a function
at refresh (AutoRefreshToken.js:17:1)
at async AuthProvide.js:16:1

However, if I create a button and call the AutoRefreshToken function there, the function works and the auth states get set. I know I am missing something, could you help me? Thanks

0 Answers
Related