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
setState in React is async, if you want to use the value after an update, you need to use :
You can try this