Home > Software design >  react native - problem with useState, fetch value?
react native - problem with useState, fetch value?

Time:12-05

I want to update the 'people' field. The problem is that the previous value goes to the state, not the current one. I don't know how to make it correct.

I am getting a value from previous rendering

const [totalPeoplem, setTotalPeople] = useState(0);

const handleUpdate = async (initialItem) => {

firestore()
    .collection('users')
    .doc(user.uid)
    .collection('city')
    .doc(itemId)
    .update({
    people: totalPeople
     }).then(() => {
      console.log('Update');

     });

  }

CodePudding user response:

You can solve it with useEffect

For example:

const [totalPeoplem, setTotalPeople] = useState(0);

useEffect(() => {
  const handleUpdate = async (initialItem) => {
    await firestore()
      .collection('users')
      .doc(user.uid)
      .collection('city')
      .doc(itemId)
      .update({
        people: totalPeoplem,
      }).then(() => {
        console.log('Update');
      });
  };
  handleUpdate()
}, [totalPeoplem]);
  • Related