Home > OS >  Delete a product on cart and localStorage
Delete a product on cart and localStorage

Time:03-07

I'm currently on student project where I'm stuck on delete product on cart page I have no problem to delete them on the front page but when it come to remove it too on localStorage honestly I don't know what to do.

I know that using localStorage.setItem allow to update it when necessary but on the code that I wrote I don't know where to put correctly.

I wrote this :

// Targeting arrays
let deleteButton = document.querySelectorAll('.deleteItem');
let localStorageProducts = localStorage.getItem('Produits');


for (let i = 0; i < deleteButton.length; i  ) {
// Get all remove buttons
let buttons = deleteButton[i];
// Link to his parent
let myData = deleteButton[i].closest('article');
let getStorageProducts = JSON.parse(localStorageProducts);


buttons.addEventListener("click",() =>
{

      getStorageProducts.forEach(localStorageProducts =>{
            if(localStorageProducts.id === myData.dataset.id){
                  // Delete the product
                  myData.remove();
                   localStorage.setItem('Produits',(JSON.stringify([localStorageProducts])));      
            }
                  
      })
      

})
    
}
<section id="cart__items">
               <article  data-id="{product-ID}" data-color="{product-color}">
                <div >
                  <img src="../images/product01.jpg" alt="Photographie d'un canapé">
                </div>
                <div >
                  <div >
                    <h2>Nom du produit</h2>
                    <p>Vert</p>
                    <p>42,00 €</p>
                  </div>
                  <div >
                    <div >
                      <p>Qté : </p>
                      <input type="number"  name="itemQuantity" min="1" max="100" value="42">
                    </div>
                    <div >
                      <p >Supprimer</p>
                    </div>
                  </div>
                </div>
              </article> 
            </section>

An example , here I have 4 products : Products in Localstorage

When I click on one of the remove button it's gonna delete 3 of them and one left :

Product left

How could I delete them one by one ?

CodePudding user response:

@Yokke i refactored your logic in this way (please read comments on commented lines) :

//LOCAL TEST START: i used these lines to test with static local logics you can ignore this
let prods = [{id: 1, prodname: 'prod1'}, {id: 2, prodname: 'prod2'}, {id: 3, prodname: 'prod3'}];
localStorage.setItem('Produits',JSON.stringify(prods));
//LOCAL TEST END.

// i used getElementsByClassName because it's native function which is supported in all browsers even old ones.
let viewArticles = document.getElementsByClassName('cart__item'); 

let localStorageProducts = localStorage.getItem('Produits');
let products = JSON.parse(localStorageProducts);

// looping on Articles instead of Buttons to be able to get product ID easily
for (let article of viewArticles) {
    article.addEventListener("click",function (ev)
    {
        // by {capturing: true}, i can access to the high clicked element
        // (which is the <article> tag in our case) by .currentTarget property
        const currentArticle = ev.currentTarget;

        // by {capturing: true}, i can access to the exactly clicked child element
        //(which is the delete button in this case by performing a check test using .target property class
        const isDeleteBtnClicked = ev.target.classList.contains('deleteItem');

        // if the child element is the delete button then 
        // delete the product and update the local storage
        if(isDeleteBtnClicked){
            // access to product id of the article
            const productId = currentArticle.dataset.id; 
            products = products.filter(prd => prd.id.toString() !== productId.toString());
            localStorage.setItem('Produits',JSON.stringify(products));
        }

    }, {capture: true}); // enable capturing instead of bubbling (top to bottom propagation)
}

for more informations about Capturing and Bubbling you can check this

  • Related