简体   繁体   中英

Get initial value of Firestore document

I am trying to make an addition of a grocery quantity in my react native app. The groceries are coming from firebase firestore with pre-defined prices, I want that when I increase the quantity, the total count of the cart_items should be correctly calculated. I am approaching this by adding it directly from the server.

The issue is, I need to be able to get only the initial price of a grocery, so I can add and subtract at will, instead, I am getting the updated price when I add the quantity, and that updated price is being added to the current price when I need to increase the quantity again. I hope you get what I mean.

const increment = async (id) => {
    const itemRef = doc(db, "cartItems", id);
    await getDoc(itemRef).then(async (snapshot) => {
      // This Line of code is supposed to capture the initial value of the price
      let price = snapshot.data().data.price;
      console.log(price);
      // This Line of code is supposed to capture the initial value of the price
      await updateDoc(itemRef, {
        quantity: snapshot.data().quantity + 1,
        data: {
          ...snapshot.data().data,
          price: snapshot.data().data.price + price,
          // I am supposed to use that initial value for this calculation
        },
      });
    });
  };

And here's for decreasing the quantity

const decrement = async (id) => {
const itemRef = doc(db, "cartItems", id);
await getDoc(itemRef).then(async (snapshot) => {
  // This Line of code is supposed to capture the initial value of the price
  let price = snapshot.data().data.price;
  console.log(price);
  // This Line of code is supposed to capture the initial value of the price
  await updateDoc(itemRef, {
    quantity:
      snapshot.data().quantity === 1 ? 1 : snapshot.data().quantity - 1,
    data: {
      ...snapshot.data().data,
      price:
        snapshot.data().data.price === price
          ? price
          : snapshot.data().data.price - price,
          // I am supposed to use that initial value for this calculation
    },
  });
});

};

So I just need to know if there's a way I can get only the initial value of the price and not the updated value. Please let me know if I need to clarify anything about the question. It's a really pressing issue for me right now.

I got my answer guys.

I just had to add an initial value that remains constant and doesn't change to my database. That's what I use to make the necessary calculations on my app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM