Remove Item from LocalStorage

I am saving a product to localStorage and I need to delete the item from localStorage. I am using

deleteItem(i){
localStorage.removeItem(i);
localStorage.setItem(i, JSON.stringify(this.items));
this.items.splice(i,1);
}

and I get the argument to the function from

<tr *ngFor="let item of items; let i = index">
<td>
<button type="button" (click)="deleteItem(i)">X</button></td>
</tr>

This isn’t working. The product is still in localStorage after executing the above code.

Hello!

But you’re removing the item after storing it. The correct way should be:

  1. Remove item from array.
  2. Remove the item from local storage.
  3. Re-add the item to local storage.

Step 2 is redundant though, since setItem would replace the contents of the element.

You’re storing the entire array as a different index on the localStorage. If you take a look at the local storage manager on your developer tools (F12, usually), you should see something like this:

And I don’t know if that’s what you really want, but seems like a bug.

Hello! You made a slight mistake in your code. I feel this might work.
deleteItem(i){
this.items.splice(i,1);
localStorage.removeItem(i);
localStorage.setItem(i, JSON.stringify(this.items));
};

The first line of code removes the item from local storage, however you did not remove the item “i” from the items array before re-adding it to the local storage. The “i” is still added on line three , because you didn’t call the splice method on the items array before setting it in the local strorage

1 Like