-1

On each page reload, I'm checking if there's a JWT cookie set and if so, set the user state. Changing the state works fine, but if I then want to log the user, the function uses the state's initial data. What's wrong here?

const useUser = (secure, needRole) => {

const router = useRouter();
const path = router.pathname;

const { user, setUser, handleUserRefresh } = useContext(UserContext);

const [isAuthenticated, setAuthenticated] = useState(false);

useEffect(()=> {

    const getUserFromCookies = async ()=> {
        await handleUserRefresh() //check for cookie, get user details
        .then((response)=> {
            setUser({
                name: response.data.name,
                email: response.data.email,
                id: response.data.id,
                role: response.data.role
            })
            console.log(user); // {name:"", email:"", id:"", role:""}
        })
        .catch((error)=> {
            // No user logged in
        });
        
    }
    if (!user.name) {
        getUserFromCookies();
    }

}, [])

return {
    isAuthenticated
}
}
export default useUser;
Fluxium
  • 100
  • 1
  • 9

1 Answers1

0

you need to add an other useEffect that triggers when user object is changed :

useEffect(()=> { 
 setAuthenticated(user && user.name)
}, [user])
سعيد
  • 1,547
  • 1
  • 14
  • 32