CartJS.cart.items not updating after item addition

Highlighted
Tourist
10 0 1
$('.purchase_button').on('click', function(e){
    e.preventDefault();
    var $this = $(this);

    var variant_id = $this.closest('div').data('product-id');
    var qty = Number($this.parent().parent().find("[name='quantity']").val());
  
    CartJS.addItem(variant_id, qty, {}, {
      "success": function(data, textStatus, jqXHR) {
        console.log(CartJS.cart.items)
        var html = '';
        CartJS.cart.items.forEach(item => {
          var price = Shopify.formatMoney(item.final_price);
          price = price.replace(/\.00$/,'');
          var price_without_currency = parseFloat(price.substring(1));
          html += `
          <li data-product-id="${item.variant_id}">
            <img src="${item.image}">
            <div class="cart_product_details">
              <h1>${item.product_title}</h1>
              <div class="quantity cart_quantity">
                <span class="plus-btn">+</span>
                <input type="text" name="quantity" value="${item.quantity}" readonly="">
                <span class="minus-btn">−</span>
                <span class="separator">|</span>
                <span class="product_total" data-product-price="${price_without_currency}">${price}</span>
              </div>
            </div>
          </li>`
        })
        
        $('.cart_products').html(html);   

      }
    })
});

So here, once the first product gets added, the CartJS.cart.items array is not updating in the "success" function, therefore, it's looping on an empty array and not changing the html, but it is updating once I add the same item (because the array is updating after the loop) what's the ideal way to solve this and keep it async?

0 Likes