I am new to learning javascript. I am saving items in localstorage and it saves successfully. I can see the result in the console also but the problem is that an old item gets replaced with a new item. I want to save each of the items in localstorage as an add-to-cart.
function addToCartClicked(event) {
var Title, Price, Image
var button = event.target
var shopItem = button.parentElement.parentElement.parentElement.parentElement
var title = shopItem.getElementsByClassName("name-of-product")[0].innerText
var price = shopItem.getElementsByClassName('product-price')[0].innerText
var image = shopItem.getElementsByClassName("hover-img")[0].src
let itemsList = {
Title: title,
Price: price,
Image: image,
}
let cartItems = {
[itemsList.Title]: itemsList
}
localStorage.setItem("productsInCart", JSON.stringify(cartItems));
cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
console.log("This is without json", cartItems);
}
>Solution :
localStorage.setItem will add that key to the localstorage of the browser, or oerwites that key’s value if it already exists.
So your old data will be overwritten once you executes localStorage.setItem
What you have to do is, you have to extract the current value in local storage using localStorage.getItem, add the new value to that extracted value and update the local storage with the new value that consist of old and new data.
So your code will be something like below
function addToCartClicked(event) {
var Title, Price, Image
var button = event.target
var shopItem = button.parentElement.parentElement.parentElement.parentElement
var title = shopItem.getElementsByClassName("name-of-product")[0].innerText
var price = shopItem.getElementsByClassName('product-price')[0].innerText
var image = shopItem.getElementsByClassName("hover-img")[0].src
let itemsList = {
Title: title,
Price: price,
Image: image,
}
let cartItems = localStorage.getItem("productsInCart");
cartItems = cartItems ? JSON.parse(cartItems) : {};
cartItems[itemsList.Title] = itemsList;
localStorage.setItem("productsInCart", JSON.stringify(cartItems));
cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
console.log("This is without json", cartItems);
}