Home > Mobile >  Unable to set state value using useState in react
Unable to set state value using useState in react

Time:10-28

When I submit the info, the console.log gives me back a user.user.uid value. But when setting the value to a variable using useState, it sets the value as null and passes null value to userInfo function. userInfo is also an async function. Why is that?

  const handleSubmit = async (e, email, password) => {
    e.preventDefault();
    try {
      const user = await createUserWithEmailAndPassword(auth, email, password);
      console.log(user.user.uid);
      await setUserId(user.user.uid);
    } catch (e) {
      console.log(e);
    }
    await userInfo(email, password, userId);
  };

CodePudding user response:

If your setUserId state setter is not a promise (https://stackoverflow.com/a/58326822/15814542), you cannot await it.

This causes await userInfo(..., userId) to run with userId set to null.

You could

let userId = ...;
try{userId = ...}
await userInfo (email, password, userId);
setUserId(userId)

CodePudding user response:

As the state updates are maybe async you could do it as

const handleSubmit = async (e, email, password) => {
  e.preventDefault();
  try {
    const user = await createUserWithEmailAndPassword(auth, email, password);
    setUserId(user.user.uid);
    await userInfo(email, password, user.user.uid); // pass uid directly as so
  } catch (e) {
    console.log(e);
  }
};

If the result is not being used from userInfo using await is not required too ...

  • Related