0

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

2
  • 1
    Do you expect data to be an object or a number? Object.values is used to return an array consisting of the values within an object. parseFloat returns NAN when used against an array. if data is a number, just reference it directly. let newNumber = data + 1; if data is an object of cart items, you need to determine it's length. Try let number = currentBasket.length(); Commented Mar 31, 2021 at 21:53
  • Thanks Kevin, pointed me in the right direction. Saw the NAN return you mentioned, I was expecting it to be a number but it was an array. I have now got it working with numbers but the code still seems to keeps looping? Commented Mar 31, 2021 at 22:26

1 Answer 1

3

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', ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.