Maureen Moore

Maureen Moore

  • NA
  • 206
  • 0

Don't Add Product if Product is already in localStorage

Aug 8 2020 8:51 AM
I have a shopping cart and I only want the products to be set if they don't already exist in localStorage. If the product is already in localStorage, then no new product should be added. Then I need to update the quantity if the item is already set. The code that I have so far sets the product even if the product already exists and it doesn't update the quantity.
  1. public onSubmit(id, thumbnail, quantity, product_name, product_price){  
  2.   
  3. var data = {  
  4. id,  
  5. thumbnail,  
  6. quantity,  
  7. product_name,  
  8. product_price  
  9. };  
  10.   
  11. var retrieverObject = localStorage.getItem('items');  
  12. var retrieveObject = JSON.parse(retrieverObject);  
  13. retrieveObject.forEach(el => {  
  14. if (el.id == id){  
  15. this.quantity += quantity;  
  16. else {  
  17. this.items.push(data);  
  18. localStorage.setItem(this.storageKey, JSON.stringify(this.items));  
  19. }  
  20. });  
  21. }  

Answers (3)