2

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

BogdanB
  • 139
  • 10
  • Try using useEffect and token or userIsLoggedIn as a dependency and console.log inside that hook. Also, you can try useCallback whenever you are calling a function based on dependency – Reza Ghorbani Dec 22 '21 at 04:36

1 Answers1

1

You cannot rely on the value of userIsLoggedIn to have the value you passed to setUserLoggedIn immediately.

If you want to keep track of the userIsLoggedIn variable, you might consider something like this:

React.useEffect(() => {
  console.log(userIsLoggedIn)
}, [userIsLoggedIn])
Willow
  • 1,132
  • 5
  • 20
  • the problem is when I try to console.log(context.userIsLoggedIn) in the component I'm using the context in, not the actual component function of the context. It this case using useEffect doesn't seem to help, it still prints out false the first time around, as if the variable wasn't updated quick enough – BogdanB Dec 22 '21 at 04:51
  • 1
    It's because your default value in context is set to false. So the first render, it is false until it rerenders once correctly. – Andrew Dec 22 '21 at 05:25