imconnor
imconnor

Reputation: 415

JavaScript infinite loop when updating firebase Realtime database

I'm trying to allow non-signed in users the ability to add items to a basket. When the button is clicked the code below is run. By default the basket value doesn't exist, so the if statement should create a value. The else statement will add 1 to existing value.

This seems to cause an infinite loop and the number in the database jumps to 1016. I've probably approached this in the wrong way and can't see how to stop this.

function addToBasket(sessionID){
  firebase.database().ref('tempUser/' + sessionID).on('value', function (snapshot) {
    var data = snapshot.val();
    
    if (data == null) {
      //update
      firebase.database().ref('tempUser/' + sessionID).set({
        basket: 1,
      });
    }
    
    else {
      //get basket number
      var currentBasket = Object.values(data);
      //turn string into a integer 
      let number = parseFloat(currentBasket) ;
      //add one to the value
      var newNumber = number + 1;
      //upload new number to db
      firebase.database().ref('tempUser/' + sessionID).set({
        basket: newNumber,
      });
    }

  });
}

Firebase Real Time Database

Thank you in advance for any help or advice, Connor

Upvotes: 0

Views: 716

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

You're attaching a permanent listener to tempUser/$sessionID in your database. This means that Firebase immediately calls your callback method with the current value in the database, and then calls the same callback each time the value changes.

Since inside this call, you are changing the data with tempUser/$sessionID, that triggers the same callback again. Which then makes another change to tempUser/$sessionID, which triggers the callback again. And again, and again...

If you only want to change the value once, use once() instead of on():

 firebase.database().ref('tempUser/' + sessionID).once('value', ...

Upvotes: 3

Related Questions