skip to Main Content

In the auth and login function, the data returned is correct, but when I save it to state, it just disappears

export const useAuth = () => {
    const [user, setUser] = useState(null);
    return {
        user,
        async login({mail, password, stayLoggedIn}) {
            const res = await logIn({mail, password, stayLoggedIn})
            console.log(res.data)
            if(res.status===200) setUser(res.data)
            return res;
        },
        async auth() {
            try {
                const res = await autoLogin();
                console.log(res.data) // correct data
                setUser(res.data)
                console.log(user) // null
                return res;
            } catch (e) {
                console.log(e)
            }
        },
        async logout() {
            setUser(false)
        }
    }
}

Expected result was to have the user data saved to state, then pass it as context to the rest of the app.

2

Answers


  1. setState in React is async, if you want to use the value after an update, you need to use :

    useEffect(() => {
       console.log(user);
    }, [user]));
    
    Login or Signup to reply.
  2. You can try this

    
    export const useAuth = () => {
        const [user, setUser] = useState(null);
    
        useEffect(() => {
            auth(); // Check if user is already logged in when the component mounts
        }, []);
    
        const login = async ({mail, password, stayLoggedIn}) => {
            try {
                const res = await logIn({mail, password, stayLoggedIn});
                if (res.status === 200) {
                    setUser(res.data);
                }
                return res;
            } catch (error) {
                console.log(error);
                return error.response;
            }
        };
    
        const auth = async () => {
            try {
                const res = await autoLogin();
                if (res.status === 200) {
                    setUser(res.data);
                }
                return res;
            } catch (error) {
                console.log(error);
            }
        };
    
        const logout = async () => {
            setUser(null);
        };
    
        return {
            user,
            login,
            auth,
            logout
        };
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search