I have a javascript file that loads when the page loads. This file defines two variables (one for the shopping cart items and one for the count).
This script also contains a subscribe
that fires whenever the cart is updated.
When I add items to the cart, remove items from the cart or update the cart, this subscribe
is hit and I am able to execute logic inside there.
This is fine for most however when a user changes the qty
of an item in the cart, I can never get the previous qty
.
var cart = customerData.get('cart');
// Define variables to check against inside the subscribe
var count = cart().summary_count;
var currentItems = [...cart().items];
// Watch the cart
cart.subscribe(function () {
// If the count has changed
if (cart().summary_count !== count) {
for(let i =0; i < cart().summary_count; i++){
var foundItem = currentItems.find(x => x.product_id == cart().items[i].product_id);
var currentItem = cart().items[i];
// Both of these values are the same
if(foundItem.qty < currentItem.qty){
var qtyChange = currentItem.qty - foundItem.qty;
}
}
}
// Set the count to the new value
count = cart().summary_count;
// Set the new currentItems array
currentItems = cart().items;
});
The cart().summary_count
updates but the qty against the item updates in both the duplicated items array defined outside the subscribe as well as the cart().items
array (which I'd expect).
I have noticed that the value for qty in the array defined outside the subscribe changes to a string and the cart().items
version of the qty is an int.
Below is a screenshot of what I am seeing in dev tools. I have updated the qty in the cart for item_id 269
Am I missing something here?