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,
});
}
});
}
Thank you in advance for any help or advice, Connor

datato be an object or a number? Object.values is used to return an array consisting of the values within an object.parseFloatreturnsNANwhen used against an array. ifdatais 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. Trylet number = currentBasket.length();