3

I have certain items on a page where by, when 'addToCart' is clicked, the respective item is saved in the local storage from which it is retrieved and displayed in the cart. The format with which they are sent to the local storage is cartItems={[product.title]:product} which is then stored using the line localStorage.setItem('productsInCart',JSON.stringify(cartItems)); When for instance an item called Jack Daniels 1L is tapped and consequently stored in the local storage, I get a table the that looks like below in the local storage:

Key Value
    
cartNumbers 1
productsInCart  {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}
totalCost   3850

Once the product is displayed in the cart, there's a delete button which can be used to delete it, especially from the local storage i.e I wish to delete the following entry from the local storage {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}. Below is a function called when the delete button has been tapped that I hoped would have worked but in vain:

function removeCartItem(event){

    var buttonClicked = event.target;
    
     if (buttonClicked) {
        var current = buttonClicked.parentElement.parentElement;
        var title = current.querySelectorAll('.cart-item-title')[0].innerText;
        var cartItems = localStorage.getItem('productsInCart');
            cartItems = JSON.parse(cartItems)

        if (cartItems) {
            var itemKeys = Object.keys(cartItems);
                for (var i = 0; i < itemKeys.length; i++) {
                    var key = itemKeys[i]
                    console.log(key)//in this case prints: Jack Daniels 1L, as desired.
                    if (title === key ) {
                        localStorage.removeItem(key)
                    }
                }
        }
    }
} 

What is the best way to proceed?

3
  • PS: "Never" use event.target unless you really know what you're doing. Stick always to event.currentTarget instead. (Put i.e: a <i> inside your button and you'll see why). Commented Dec 27, 2020 at 12:33
  • buttonClicked.parentElement.parentElement.parentElement.... is just waiting for you to slightly modify the HTML markup to fail beautifully the JS you wrote. Use .closest() instead. Commented Dec 27, 2020 at 12:36
  • Try not to use text as your unique identifiers (i.e: "Jack Daniels 1L"). Always try to use some UID. Store such UID inside data-* attributes like i.e: data-id="245" given this data: {"245": {id: "245", "title":"Jack Daniels 1L","cost":3850,"cartConts":1}} Commented Dec 27, 2020 at 12:38

1 Answer 1

4

There's no LocalStorage key to remove (in your specific case) - since your only LS key is your actual productsInCart in its entirety, which is holding pretty much all the cart data.
You simply want to delete a property/value from an object. Therefore, use Object's delete.
After deleting your Object entry, simply store back into LS the entire stringified productsInCart Object data.

// Get <button> and UID
const EL_button = event.currentTarget;
const id = EL_button.closest("[data-id]"); // i.e: "245"

// Parse LS 
const cartItems = JSON.parse(localStorage.productsInCart || "{}");  // Object

// Check if exists
if (cartItems.hasOwnProperty(id)) {
  // Exists in LS cart! 
  // Delete it!
  delete cartItems[id];
  // Update LS:
  localStorage.productsInCart = JSON.stringify(cartItems);
  // Do something with that button:
  EL_button.textContent = "Add to cart";
}

The above code is given a HTML like i.e:

<div data-id="245">
  Juicy Peach 3dl - 2$
  <button type="button" data-id="245">Remove from cart</button> 
</div>
<div data-id="455">
  Energy overflow 1L - 5$
  <button type="button" data-id="455">Remove from cart</button> 
</div>

and a JSON data like i.e:

{
  "245" : {"id":"245", "name":"Juicy Peach 3dl", "price":"2", "cartConts":1},
  "455" : {"id":"455", "name":"Energy overflow 1L", "price":"5", "cartConts":0},
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.