Home > Software engineering >  Does use useState inside useEffect doesn't works?
Does use useState inside useEffect doesn't works?

Time:10-17

I have this function getting called inside useEffect. The output that I am getting is user idddd is null 616830f1491ef15dc0ba5a6a .While id variable is giving me proper value in console.log statement but userId is still null. I am not sure why is it happening.

function Component() {
const [userId, setuserId]= useState(null);

useEffect(()=>{
   getUserId()
        .then((id)=>{
          setuserId(id);
          console.log("user idddd is", userId, id);
         
        })
},[])

  function getUserId() {
    let id = localStorage.getItem("userId");
    return new Promise((resolve, reject)=>{
      if(id){
        resolve(id);
      }
      reject();
    })
  }
.
.
.
}

CodePudding user response:

Even though you set the state in useEffect, it will only update on the next render of the component. This is why it is null when you console.log() right after you set it.

CodePudding user response:

you cant expect javascript to executesetuserId to update the value then come back to console.log your updated userId

  setuserId(id);
  console.log("user idddd is", userId, id);

setUserId will update the value right after your whole .then() finishes

  • Related