Reputation: 49
I have 4 buttons in HTML. In JS, I added an event listener to them (through a loop) so that everytime a button is clicked, I get the value and the name of the button. I put the value and name in an object and send the object to the local sotrage. The problem is that each time a button is clicked, the new values in the local stroage overwrite the previous entered ones. What should I do to keep all the values sent to the local store after a button is clicked? I´ve been reading and testing different options but nothing works.
My HTML
<div>
<button class="add-cart" type="button" name="peperonni" value=".25">
Add to cart
</button>
<button class="add-cart" type="button" name="meatballs" value=".35">
Add to cart
</button>
<button class="add-cart" type="button" name="mushrooms" value=".40">
Add to cart
</button>
<button class="add-cart" type="button" name="peperonni" value=".20">
Add to cart
</button>
</div>
My JS
let addCart = document.querySelectorAll('.add-cart');
addCart[i].addEventListener('click', () => {
let name = addCart[i].name;
let price = addCart[i].value;
const menuItem = {
name: name,
price: price,
};
window.localStorage.setItem('ProductsInCart', JSON.stringify(menuItem));
});
}
Upvotes: 1
Views: 2328
Reputation: 4199
addCart[i].addEventListener("click", () => {
// get items from localStorage, or declare new one if not exist
let menuItems = localStorage.getItem("ProductsInCart") || '[]';
menuItems = JSON.parse(menuItems);
// declare and add the new item
menuItems.push({ name: addCart[i].name, price: addCart[i].value });
localStorage.setItem("ProductsInCart", JSON.stringify(menuItems));
});
Upvotes: 3
Reputation: 11
The entry is being overwritten because you are always using the same key to store the data. Please change the key every time to prevent overwriting the previous entry.
window.localStorage.setItem(key, JSON.stringify(menuItem));
You can try:
let addCart = document.querySelectorAll('.add-cart');
addCart[i].addEventListener('click', () => {
let name = addCart[i].name;
let price = addCart[i].value;
const menuItem = {
name: name,
price: price,
};
window.localStorage.setItem('ProductsInCart_'+i, JSON.stringify(menuItem));
});
}
Upvotes: 0
Reputation: 1443
Push the new menu Item in the Menu Item Array
addCart[i].addEventListener("click", () => {
let menuItems = window.localStorage.getItem("ProductsInCart");
if (menuItems) {
menuItems = JSON.parse(menuItems);
} else {
menuItems = [];
}
let name = addCart[i].name;
let price = addCart[i].value;
const menuItem = {
name: name,
price: price,
};
menuItems.push(menuItem);
window.localStorage.setItem("ProductsInCart", JSON.stringify(menuItems));
});
Upvotes: 1
Reputation: 72857
To update local storage without replacing it, you need to do it in a few steps:
ProductsInCart
entry from storage.ProductsInCart
entry in your local storage.So, simply put:
Read -> Update -> Write
Upvotes: 2