Items not being saved to localStorage

It would appear that the onSubmit function below is saving to localStorage but I deployed the code to the Web and when I refreshed the page, the shopping cart got emptied. I can’t test the code after every modification because I’m in development mode and the page re-compiles when it’s refreshed but I can test it with the deleteItem function which uses splice. Splice only works on an array and when I click the delete button, the product gets cleared so that tells me it’s not using localStorage.

In the component:

items = [];

public onSubmit(thumbnail, quantity, product_name, product_price){

const data = {
   thumbnail,
   quantity,
   product_name,
   product_price
};

localStorage.setItem('items', JSON.stringify(data));
this.items.push(JSON.parse(localStorage.getItem('items')));
this.isSubmitted = true;
}

deleteItem(i){
this.items.splice(i,1);

}

In the HTML:

<tr *ngFor="let item of items; let i = index">
<td>
<button type="button" (click)="deleteItem(i)">X</button></td>
<td><img src="{{item.thumbnail}}" /></td>
<td>{{item.quantity}} </td>
<td>{{item.product_name }} </td>
<td>{{item.product_price }} </td>
<td>{{item.quantity * item.product_price  }}</td>

</tr>
1 Like

hey @makamo66,

try this,

// get items from local strorage 
storedItems = localStorage.getItem('items'))

// add stored items to items array or create new array
items = JSON.parse(storedItems) : [];

public onSubmit(thumbnail, quantity, product_name, product_price){

const data = {
   thumbnail,
   quantity,
   product_name,
   product_price
};

//push data to items array
this.items.push(data);

// update local storage after data is added to array
localStorage.setItem('items', JSON.stringify(items));

this.isSubmitted = true;
}

deleteItem(i){
this.items.splice(i,1);

}

Thanks biscuitmanz but splice still deletes the item and if it were being saved in localStorage I would have to use localStorage.removeItem()

@makamo66,

localStorage.removeItem() would remove the whole items array from your local storage, i dont think thats what you want is it?
what you should do is use splice to remove the item from the item array then update the local storage with the new items array so like this.

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

:arrow_down:

Splice should still work because the local storage is putting the items back into the array on the page load so splice will be able remove the item from the array then with the code above you can update to local storage with the new array thats had the item removed.

1 Like

Are you implementing this inside React component?

Thanks, biscuitmanz. I ended up using someone else’s code.

1 Like

@snigo No, this is angular not react.