0

I am making a basic shopping cart that pushes objects into an array using a click event handler. I managed to do this and save the objects in the array using local storage. What I want to know is how can I now remove an object from the array? When I use pop() and I refresh the page the objects are still in my array. When I use localStorage.removeItem() it ends up erasing all of my objects in the array.

I tried localStorage.removeItem but it erases all objects from my array.

Here is some of my code:

// Add to cart
var cart =  JSON.parse(localStorage.getItem('cart')) || [];

var product1 = {
    name: "product1",
    price: 90.00
};

document.getElementById("cart-button").addEventListener("click", addToCart);

function addToCart() {
    cart.push(product1.name + "<br />" + product1.price);
    localStorage.setItem('cart', JSON.stringify(cart));
    document.getElementById("cart-contents").innerHTML = cart;
}

// Remove an item from the cart
document.getElementById("remove-button").addEventListener("click", removeItem);

function removeItem() {
    removeItem(product1);
    cart.pop();
    document.getElementById("cart-contents").innerHTML = cart;
}

1 Answers1

0
// Add to cart
      var cart = JSON.parse(localStorage.getItem('cart')) || [];

      var product1 = {
        name: 'product1',
        price: 90.0
      };

      document
        .getElementById('cart-button')
        .addEventListener('click', addToCart);

      function addToCart() {
        cart.push(product1.name + '<br />' + product1.price);
        localStorage.setItem('cart', JSON.stringify(cart));
        document.getElementById('cart-contents').innerHTML = cart;
      }

      // Remove an item from the cart
      document
        .getElementById('remove-button')
        .addEventListener('click', removeItem);

      function removeItem() {
        cart.pop();
        localStorage.setItem('cart', JSON.stringify(cart));
        document.getElementById('cart-contents').innerHTML = cart;
      }

Your mistake was removeItem(product1);

Jesus Africano
  • 131
  • 1
  • 6