Maureen Moore

Maureen Moore

  • NA
  • 206
  • 0

Items not being saved to localStorage

Jul 27 2020 1:42 PM
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:
  1. items = [];  
  2.   
  3. public onSubmit(thumbnail, quantity, product_name, product_price){  
  4.   
  5. const data = {  
  6. thumbnail,  
  7. quantity,  
  8. product_name,  
  9. product_price  
  10. };  
  11.   
  12. localStorage.setItem('items', JSON.stringify(data));  
  13. this.items.push(JSON.parse(localStorage.getItem('items')));  
  14. this.isSubmitted = true;  
  15. }  
  16.   
  17. deleteItem(i){  
  18. this.items.splice(i,1);  
  19.   
  20. }  
In the HTML:
  1. <tr *ngFor="let item of items; let i = index">  
  2. <td>  
  3. <button type="button" (click)="deleteItem(i)">X</button></td>  
  4. <td><img src="{{item.thumbnail}}" /></td>  
  5. <td>{{item.quantity}} </td>  
  6. <td>{{item.product_name }} </td>  
  7. <td>{{item.product_price }} </td>  
  8. <td>{{item.quantity * item.product_price }}</td>  
  9. </tr>  

Answers (12)