0

I have this useState statement:

const [userLogged, setUserLogged] = useState();

And this is a fragment of my code in a custom hook:

await axios.post('http://localhost:3000/users/register', form).then( (res)=> {
  setUserLogged(res.config.data)
  console.log(UserLogged)
  window.location.href = "http://localhost:3001/"
});

When my callback is working, i want to set the state of userLogged using setUserLogged with the user object from res, but it doesn't work. If a do a console.log of userLogged state, i get a undefined.

I tried by passing a boolean or string to setUserLogged for testing, but its undefined too.

  • 2
    setState is asynchronous and the state value is guaranteed to be the same throughout the lifecycle of each render. The new state value won't be available until the next render cycle – pilchard Jun 27 '21 at 17:34
  • Adding to what @pilchard said. Check in useEffect which has a dependency value of your state variable, you will be able to see your updated value. – Tushar Shahi Jun 27 '21 at 17:37
  • "it doesn't work" isn't true - this code will work fine, if you log the value of `userLogged` inside the body of your function component, you will see that at some point soon after the API call resolves, it will hold the user data you require. It simply happens to still be `undefined` at the point where your current `console.log` statement is. – Robin Zigmond Jun 27 '21 at 17:48

0 Answers0