Unable to delete localStorage array item

Viewed 77

I'm trying delete individual cart items from cart, which is saved in localStroage, so far I'm only able to delete whole array via removeitem() or clear(), but I want to delete selective item by item id. Mean while I'm getting below error if I used splice. I'm learning so let me know if I need to provide more information.

deleteProduct: (index) => {
            const existingEntries = JSON.parse(localStorage.getItem("cartData"));
            existingEntries.splice(index, 1);
            localStorage.setItem("cartData", JSON.stringify(existingEntries));
        }
let cartData = window.localStorage.getItem('cartData');

const cart = {
    state: {
        cartData: cartData ? JSON.parse(cartData) : {
            foods: [],
            totalPrice: [],
            Quantities: []
        },
    },

enter image description here

enter image description here

3 Answers

Notes:

  1. cartData is a String, it's in localStorage, so it must be a String.
  2. Parse it, it's an Object
  3. cartData.foods is the array here

Code steps:

  1. get cartData from localStorage
  2. Parse it, you get a JSON Object with has a key .food
  3. Access the key, cartData.foods
  4. Splice it

Can you try

const cartData = JSON.parse(localStorage.getItem("cartData"))
if(cartData && cartData.foods) {
    const existingEntries = cartData.foods;
    existingEntries.splice(index, 1);
    localStorage.setItem("cartData", JSON.stringify(existingEntries))
}

Also you can update the totalPrice and Quantities before setItem

Try to parse your array after you get it

deleteProduct: (index) => {
        var localStorageArray =  localStorage.getItem("cartData")
        const existingEntries = JSON.parse(localStorageArray);
        existingEntries.splice(index, 1);
        localStorage.setItem("cartData", JSON.stringify(existingEntries));
    }
Related