LocalStorage overwriting data

Viewed 27

I am trying to add selected items to the cart preview and save them to local storage so I can then add them to the actual cart. But when I refresh only the last item I clicked shows up in the container. I see that even when I select items only the last one shows up in the 'Application' section of the console. Where am I going wrong?

btnAddCart.forEach(button => {
  button.addEventListener('click', function () {
    const markup = `
    <li class="index-preview-list-item">
     <img src="${this.parentElement.children[0].src}" alt="" />
     <h4 class="product-name">${this.parentElement.children[1].textContent}</h4>
      <button class="btn btn-delete">
        <i class="fa-solid fa-trash-can"></i>
      </button>
    </li>
    `;

    clearPreviewText();
    // cartPreviewContainer.insertAdjacentHTML('beforeend', markup);
    localStorage.setItem('item', markup);
    let storage = localStorage.getItem('item');
    cartPreviewContainer.insertAdjacentHTML('beforeend', storage);
    deleteItem();
  });
});

let storage = localStorage.getItem('item');
if (storage) {
  clearPreviewText();
}
cartPreviewContainer.insertAdjacentHTML('beforeend', storage);
1 Answers

Local storage is a key-value system. You're only using one, always the same, hard coded key: 'item'. So every time you set a value, you're overwriting the previous value.

You should vary the setItem key according to some scheme based on the identity of the thing your storing. Like maybe an item ID.

Related