Debuggingnightmare
Debuggingnightmare

Reputation: 83

Decrementing value in firebase using react native

I am trying to decrement the Quantity value in Firebase realtime database, when a button is clicked. However, I have tried multiple methods still unable to decrement the value. Listed below is what the structure looks like.

const database = [
  {
    Name: "Coca Cola",
    Price: "1.75",
    Quantity: "66",
  },
  {
    Name: "HaagenDaz",
    Price: "3.99",
    Quantity: "5",
  },
  {
    Name: "Trident",
    Price: "1.85",
    Quantity: "10",
  },
  {
    Name: "kitkat",
    Price: "1.20",
    Quantity: "100",
  },
];

One of the methods I used to decrement Quantity value for Trident to 9 is: Quantity: firebase.firestore.FieldValue.increment(-1) the result was:

{
  "Name": "Trident",
  "Price": "1.85",
  "Quantity": {
    "d_": {
      "J_": -1,
      "_methodName": "FieldValue.increment"
    }
  }
}

the expected result should've been:

{
  Name: "Trident", 
  Price: "1.85", 
  Quantity: "9"
}

I posted the code below:

Object.values(this.state.mylist).map((key) => {
  const target = key;
  const string = this.state.paredString;

  console.log("Quantity:", target.Quantity);
  // const ref_forUpdate = firebase.database().ref("Product Name");
  // const decrement = firebase.firestore.FieldValue.increment(-1);

  const name = target.Name;
  const qty = target.Quantity;
  // const decrement = firebase.firestore.FieldValue.increment(-1);
  for (let i = 0; i < string.length; i++) {
    if (target.Name == string[i]) {
      // let temp = target.Quantity
      firebase
        .database()
        .ref("Product Name/" + name)
        .update({
          // Quantity:  firebase.firestore.FieldValue.increment(-1) //<------ creates a new sub-branch under Quantity
          // Quantity: qty - 1 ,  <------ Quantity in realtime database keeps decreasing without stopping
        });
      console.log("Matched:", target);
    } else {
      console.log("Not_matched2");
    }
  }
  console.log("\n");
});

Upvotes: 0

Views: 473

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

You're using the operator for Firestore, but are writing to the Realtime Database. While both databases are part of Firebase, and both support atomic increments/decrements, the API is different.

For the Realtime Database, the field is named ServerValue.increment(), so:

firebase.database().ref("Product Name/" + name).update({
  Quantity: ServerValue.increment(-1)
})

Upvotes: 2

Related Questions