I am using a context state variable to store my token value when user signs in. And using that token through out my application.
When I log in, the token is console logged on the login page. But it gives empty value on other pages even though I am using the context in all the files.
AuthContext.js
export const AuthContext = createContext();
export const AuthProvider = (props) => {
const [authToken, setAuthToken] = useState("");
const [authProtected, setAuthprotected] = useState(true);
return (
<AuthContext.Provider
value={{
token: [authToken, setAuthToken],
authProtect: [authProtected, setAuthprotected],
}}
>
{props.children}
</AuthContext.Provider>
);
};
Login.js
const userAuth = (e) => {
e.preventDefault();
Axios.post(authApi, loginInfo).then((res) => {
setJwtToken(res.data.idToken.jwtToken);
});
};
console.log(jwtToken);
After log in, I use this in one of my pages and it logs an empty value
const { token } = useContext(AuthContext);
const [jwtToken, setJwtToken] = token;
console.log(jwtToken);