Increment quantity in the cart and save in localStorage and print it

Viewed 542

I want to ask a question that is related to my project that I am working on. I have created a shopping cart and it has add and delete buttons to increase and decrease the quantity of the item. Now the problem lies in the adding part as I am unable to increment the quantity in the localStorage

Here's my Code:

For Delete (Working)

function dlte(e) 
{
    let items = [];
    JSON.parse(localStorage.getItem('items')).map(data=>{
    if(data.id != e.parentElement.parentElement.children[0].textContent)
    {
         items.push(data);
    }
    });
    localStorage.setItem('items', JSON.stringify(items));
    alert("Item deleted from Cart");
    window.location.reload();
}


For Adding (Not working) 

function add(e)
{
    // I have tried many things but can't figure out how to make it so please help me on this 
}

I would be grateful if anyone can step up and help me on this. Thanks in advance!!

2 Answers

I am not sure why you had a problem in saving to localStorage ​

function add(content)
{
    let items = JSON.parse(localStorage.getItem('items')) || [];
    items = [...items, {id: content}] 
   // if textContent is object you can replace content with {id: content}

    localStorage.setItem('items', JSON.stringify(items));

    alert("Item added to Cart");
    window.location.reload();
}

this is how you add an item to localStorage

This can be achieved in three simple steps.

  1. Get the existing list from localStorage.
  2. Add/Remove item to/from existing list.
  3. Stringify and set updated list back to localStorage.

function dlte(e) {
    const id = e.parentElement.parentElement.children[0].textContent;
    
    const existingData = JSON.parse(localStorage.getItem('items')) || [];
    const filteredData = existingData.filter(data=> data.id !== id);
    localStorage.setItem('items', JSON.stringify(filteredData));
    window.location.reload();
}


function add(e) {
    const existingData = JSON.parse(localStorage.getItem('items')) || [];
    existingData.push(e); // construct required data to be stored in localstorage.
    localStorage.setItem('items', JSON.stringify(existingData));
    window.location.reload();
}

Related