0

I have to calculate the total price from a bunch of products stored in firebase. Since in firebase each product will be returned separately, how can I know when the total is completely calculated?

For example:

var total = 0;
firebaseApp.database().ref('/products/').once('value')
.then(function(snapshot) {
    var product = snapshot.val();
    total += product.price;
});

If I have 12 products, the total can only be returned once all those products are retrieved from the database so it's not possible for me to use the variable total until I'm sure all the products are fetched.

Emilio Rodriguez
  • 5,709
  • 4
  • 27
  • 32
  • 1
    You are right. I would suggest saving the total price to an extra node. This way you won't have to wait to know what the total price is. – Rodrigo Ehlers Jan 10 '17 at 12:43

1 Answers1

3

I think you should restructure your data to look something like this

products
    -product1
    -product2
    -product3
     .....

selected_products
    user1:
       -products_list:
            -product2: true
            -pruduct3: true
            -product6: true
       -total_price: 140

This way, you won't have to worry about calculating the prices on the client-side. Just add up the prices as the user selects the products.

If that's not the use case (a user selecting products), meaning that you need the total price for other reasons, then this approach won't be helpful.

Edit:

If all you need is to calculate the price of all products(not sure why), you can listen to child_added events:

var totalPrice = 0;
firebaseApp.database().ref(`/products/`).on('child_added', function(snapshot){
    var product = snapshot.val();
    totalPrice += product.price;
})

When all of this is done, you should have a variable with the price value of all products combined.

Similarly, you could achieve the same result with a once('value') call.

firebaseApp.database().ref(`/products/`).once('value', function(snapshot){
    snapshot.forEach(function(productSnapshot){
        totalPrice += productSnapshot.val().price;  
    })
})