简体   繁体   中英

LocalStorage overwriting data

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM