Home > Enterprise >  Why am I not able to set my state using useState and send the state to firebase realtime database at
Why am I not able to set my state using useState and send the state to firebase realtime database at

Time:12-30

I am receiving the request in firebase but it is only showing me empty results (as initialized inside useState hook). It always shows the output of previous state even though I am using async/await to fetch.

const [user, setUser] = useState({
    name: "",
    phone: "",
  });

async function postData(data) {

    setUser(data);

    const { name, phone } = { ...user };

    const res = await fetch(
      "https://react-form-f1d90-default-rtdb.firebaseio.com/react-form.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name,
          phone,
        }),
      }
    );
    if (res) {
      console.log("success");
      alert("success");
    }
  }

CodePudding user response:

setState happens asynchronously, so you cannot set the value and use it in the next line, you will have to wait for the next re-render. Here you should use the value from data directly instead of taking it from the state. Or you can do the api fetch inside a useEffect hook, where you will watch for any changes in user state. Like below

useEffect(() => { //Make the fetch call here using state value }, [user])

CodePudding user response:

As Vishnu already answered, setting state is an asynchronous operation in React, so by the time your const { name, phone } = { ...user } runs, the state hasn't been updated yet.

Instead, you can simply read the same properties from data directly:

setUser(data);

const { name, phone } = { ...data };
  • Related