I have been trying to implement a cart function to my e-commerce . In this cart function when ever I add an item, if its already present in the cart we must increase the quantity. Everything works fine but whenever I refresh the browser or add a new item the values get reverted. How can I fix this.
My frontend is ember.js v3.4.4 and Backend Ruby on Rails v7.0.2.3
The addon I'm using for localstorage is ember-localstorage-addon
Below I have attached a snippet how I add elements to the cart
// app/service/shopping-cart.js
addItem(itemId){
const itemArray = this.itemsIds.content;
const index = itemArray.findIndex(object => object.id === itemId.id);
const itemElement = itemArray[index];
console.log(itemElement);
if(itemElement){
console.log(itemId);
const quantityOfAddedElement = parseInt(itemId.quantity) + parseInt(itemElement.quantity);
console.log(quantityOfAddedElement);
const totalPrice = parseInt(itemId.price) + parseInt(itemElement.price);
itemElement.quantity = quantityOfAddedElement;
itemElement.price = totalPrice;
console.log(quantityOfAddedElement);
}
else{
this.get('itemsIds').addObject((itemId));
}
}
// app/controller/product.js
actions:{
addToItem(model){
const id = model.id;
const title = model.title;
const quantity = this.quantity;
const images = model.images;
const price = quantity * model.price;
const dbQuantity = model.quantity;
this.shoppingCart.addItem({
id,
title,
price,
quantity,
images,
});
},
}
Aucun commentaire:
Enregistrer un commentaire