[Vuejs]-Data not properly stored in shopping cart

3👍

The reason why you have total quantity of 2 every time you test could be because you called add product once and then on your next line, you called cart.addProduct in console log again. You should store the results and then console log to prevent the double adding

cart.addProduct(singleProduct, singleProduct._id);
console.log(cart.addProduct(singleProduct, singleProduct._id)); // Remove this line

Change to this

const response =  cart.addProduct(singleProduct, singleProduct._id);
console.log('Cart response: ', response);

Update 1 from the comment question:
The reason why you keep getting total quantity 1 over and over again, I would think it is because you did not update your oldCart’s qty. So you should return the storedItem after your addProduct and update oldCart.
.

Update 2
Ignore update 1, I saw the issue. The reason why totalQty 1 over and over again is because you create new cart on API call.

Update 3 Updated your addProduct code:
I noticed some errors in the code
e.g.
storedItem = this.productItems = {item: item, qty: 0, price: 0};

module.exports = function Cart(oldCart) {
    this.productItems = oldCart.productItems || {};
    this.totalQty = oldCart.totalQty || oldCart.totalQty==0.00;
    this.totalPrice = oldCart.totalPrice || oldCart.totalPrice==0.00;
   
    this.addProduct = function(item, id) {
        let storedItem =  {item: item, qty: 0, price: 0};
        // Update here        
        if (this.productItems){
 
          console.log("Stored item full!")
          storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}
        }
        console.log("totalQty: ",this.totalQty);

        console.log("Quantity 1: ",storedItem.qty);
        storedItem.qty++;
        console.log("Quantity 2: ",storedItem.qty);
        storedItem.price = storedItem.item.price * storedItem.qty;
        
        this.totalQty ++;
        this.totalPrice += storedItem.price;
        
    }
    }

    this.generateArray = function () {
        let arr = [];
        for (let id in this.productItems) {
            arr.push(this.productItems);
        }
        return arr;
    }};

Leave a comment