Jimeblue
Jimeblue

Reputation: 49

How to prevent local storage overwriting values using JS

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

Answers (4)

Nimer Awad
Nimer Awad

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

Smart IT
Smart IT

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

kzrfaisal
kzrfaisal

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

Cerbrus
Cerbrus

Reputation: 72857

To update local storage without replacing it, you need to do it in a few steps:

  1. Get the ProductsInCart entry from storage.
    (if it doesn't exist, create an empty array)
  2. Add the new cart item to your array.
  3. Save this new / updated array back into the ProductsInCart entry in your local storage.

So, simply put:

Read -> Update -> Write

Upvotes: 2

Related Questions