how can i store all items in local storage in javascript?

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);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top