Reputation: 11
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,
});
},
}
Upvotes: 0
Views: 265
Reputation: 6338
You can read from and write to local storage in Ember.js using plain JavaScript:
// reading shopping cart items from local storage
const shoppingCartItems = JSON.parse(
window.localStorage.getItem('shoppingCartItems')
);
// writing shopping cart items to local storage
shoppingCartItems.push('myItemId');
window.localStorage.setItem(
'shoppingCartItems',
JSON.stringify(shoppingCartItems)
);
Additionally you should listen for local storage events caused by changing local storage in another browser tab and update your local state accordingly.
To ease all this, I have written the ember-local-storage-decorator. It provides a @localStorage
decorator. A class property decorated with it will reflect the local storage value. It is integrated with autotracking.
Upvotes: 1