0

I am trying to add the indexes inside my array, but it's acting like it's empty. But when do a console log, I can see the items inside the array. Why is it doing that? The code im using is below:

 /***********CART**********/
 const cartFeed = document.querySelector("#cartFeed");
 const c = document.querySelector("#cartTotal");
 const addingPrices = [];

 db.collection('shoppingSession').doc(this.browserSession).collection('inCart').get().then(function (querySnapshot) {
     querySnapshot.forEach(function (doc) {
         
         var idName = doc.id;
         var title = doc.data().title;
         var qty = Number(doc.data().qty);
         var price = Number(doc.data().price);
         var itemTotal = qty * price;
         var orderTotal = 90.00;
         var thiss = orderTotal.toFixed(2);

         addingPrices.push(itemTotal);

         cartFeed.innerHTML += " \
            <div'>\
                <table>\
                    <tr>\
                        <td>" + title + "</td>\
                        <td>" + qty + "</td>\
                        <td class='itemTotal'>" + itemTotal + "</td>\
                    </tr>\
                </table>\
            </div>";
     });
 });

//Add the prices in the array

var sum = 0;
for (var i = 0; i < addingPrices.length; i++) {
  sum += addingPrices[i]
}

console.log(addingPrices);
davis
  • 21
  • 3

1 Answers1

0

This is a sync/async problem. The code to look at each index and log it will run before the code that pushes items into the array. You’ll have to move your logic to read the array into the same callback as the logic that is pushing to it, or find some alternative means of making that code run after the callback to your querySnapshot has been called.

Ben Steward
  • 2,338
  • 1
  • 13
  • 23