I’m working on auth in my app, so I created a context to manage it:
import React, { useState } from "react";
const AuthContext = React.createContext({
token: "",
isLoggedIn: false,
login: (token) => { },
logout: () => { },
});
export const AuthContextProvider = (props) => {
const [token, setToken] = useState(null);
const [userIsLoggedIn, setUserLoggedIn] = useState(false)
const loginHandler = async (token) => {
setToken(token);
setUserLoggedIn(true)
console.log(userIsLoggedIn) //prints false
};
const logoutHandler = () => {
setToken(null);
setUserLoggedIn(false)
};
const contextValue = {
token: token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return (
<AuthContext.Provider value={contextValue}>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContext;
The problem is that when I call context.login(‘some token’) from an outside component and then console.log(context.isLoggedIn) I get false the first time, but if I call context.login(‘some token’) once again I get true. Every succesive time after that I get true now. It might have to do with the fact the “console.log(userIsLoggedIn)” inside the loginHandler says “false” (the first time the context.login is called) even though the setUserLoggedIn is right above it. I think the userIsLoggedIn variable is changed after the context is updated in the component it’s used in, but I don’t know how to fix that.
I will appreciate any help on this