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);
When the page reloads, the context is recreated. You need to use a useEffect within the context to refetch the information from the backend and save the token in case you are saving to some cookie or localstorange.
Put the token in the cookie and when it switches pages, retrieve the cookie by useEffect to save again in context
Note: when you switch pages, everything in the context is recreated, so when the page goes to get something from the context, it will be empty