Lucdabomb
Lucdabomb

Reputation: 261

React State is rolling back to previous value

I have a problem which I could not figure out. I have this function which calculates the total price:

const [totalPrice, setTotalPrice] = useState(0);

const calcTotalPrice = (itemss) => {
  var sum = null;

  itemss.forEach(function (item) {
    sum += item?.Quantity * item?.Prijs;
  });

  setTotalPrice(sum);
  console.log(totalPrice);
};

It works great, but when I update the quantity of a product the state does not update. Well, it does but then rolls back to it's previous value. Here is the output I am getting:

570
443
467

Which is very weird. The top value is the new value, the second is the old and I don't know where the third one is coming from. The function is called everytime the function getItems() is called:

async function getItems() {
  setLoading(true);
  db.collection(`rooms/${roomId}/Items`).onSnapshot((querySnapshot) => {
    const itemss = [];
    querySnapshot.forEach((doc) => {
      itemss.push(doc.data());
    });
    setItems(itemss);
    calcTotalPrice(itemss);
    setLoading(false);
  });
}

useEffect(() => {
  getItems();
}, []);

I don't get what I am doing wrong here. Any help would be much appreciated.

Upvotes: 0

Views: 357

Answers (1)

michael
michael

Reputation: 4173

setTotalPrice(sum); won't reflect totalPrice immediately because setting state function is asynchronous. That's why console.log doesn't seem to be working properly.

Also, onSnapshot listener will be called every time collection data is changed (added/modified/removed). Here's an example for your information.

db.collection("cities").where("state", "==", "CA")
    .onSnapshot(function(snapshot) {
        snapshot.docChanges().forEach(function(change) {
            if (change.type === "added") {
                console.log("New city: ", change.doc.data());
            }
            if (change.type === "modified") {
                console.log("Modified city: ", change.doc.data());
            }
            if (change.type === "removed") {
                console.log("Removed city: ", change.doc.data());
            }
        });
    });

Upvotes: 1

Related Questions