I have a code where when the add button is clicked, it sums up the value of two objects properties and update it. When you use a "+" button to add an item, it works but whenever the user manually inputs the amount to add, instead of adding them up, it connects it like a string.
Example:
Where 5100 + 122222 should be 127322. Here's my code snippet:
JS Function:
var tobeSaved = store.getters.printCart;
if(tobeSaved.length){
if(sessionStorage.length){
var existingCart = JSON.parse(sessionStorage.cart);
var size = Object.keys(existingCart).length;
//console.log(existingCart);
tobeSaved.forEach(tobeSaved => {
let obj = existingCart.find(ob => ob.itemID === tobeSaved.itemID);
console.log(obj);
if(obj!==undefined){
obj.itemQuantity+=tobeSaved.itemQuantity;
existingCart.itemQuantity = obj.itemQuantity;
let myObj_serialized = JSON.stringify(existingCart);
sessionStorage.setItem('cart', myObj_serialized);
} else{
existingCart.push(tobeSaved);
let myObj_serialized = JSON.stringify(existingCart);
sessionStorage.setItem('cart', myObj_serialized);
}
})
}
else{
let myObj_serialized = JSON.stringify(tobeSaved);
sessionStorage.setItem('cart', myObj_serialized);
}
}
}
EDIT: Here's the User Input part
<div class="product__details__quantity d-flex justify-content-center">
<div class="quantity">
<div class="pro-qty">
<input type="number" v-model="quantity" >
</div>
</div>
</div>
Edit #2: Added vuex code
const store = new Vuex.Store({
state:{
cartItem: [],
cartCount: 0
},
mutations:{
addCart(state, payload){
this.state.cartItem.push(payload);
},
addCount(state, payload){
state.cartCount+=payload
},
},
actions:{
},
getters:{
printCart(state){
return state.cartItem;
},
counter(state){
return state.cartCount;
}
}
});
EDIT #3. Here's the button that passes the data to vue
<button type="button" class="btn btn-success btn-block" data-dismiss="modal" @click="addCart({
itemID: selectedUser.id,
itemName: selectedUser.item_name,
itemPrice: variant.default_price,
itemQuantity: quantity
})">Add to Cart</button>
AddCart:
addCart: function(cartdets){
this.quantity = 1;
var cartItems = store.getters.printCart;
//console.log(cartItems);
var filtercart = cartItems.some(function(cart){
return cart.itemID === cartdets.itemID
});
//console.log(filtercart);
if(!filtercart){
store.commit('addCart', cartdets);
store.commit('addCount', 1);
} else{
store.commit('addCart', cartdets);
}
}