Maureen Moore

Maureen Moore

  • NA
  • 206
  • 0

Cannot read property 'storageKey' of undefined

Aug 7 2020 2:28 PM
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. Later I will update the quantity if the product already exists in localStorage but I haven't reached that step yet. When I try to set the item when the id isn't in localStorage, I get the TypeError: Cannot read property 'storageKey' of undefined
 
  1. storageKey = 'MyDataStorageKey';  
  2.   
  3. public onSubmit(id, quantity, product_name){  
  4.   
  5. var data = {  
  6. id,  
  7. quantity,  
  8. product_name,  
  9. };  
  10. var retrieverObject = localStorage.getItem('items');  
  11. var retrieveObject = JSON.parse(retrieverObject);  
  12. this.items.push(data);  
  13.   
  14. retrieveObject.forEach(function(el){  
  15. alert("This is the storage id " + el.id);  
  16. if (el.id == id){  
  17. alert(el.id + " same product");  
  18. else {  
  19. alert("this id is not in storage ");  
  20. //error returns for the following line of code  
  21. localStorage.setItem(this.storageKey, JSON.stringify(this.items));  
  22. }  
  23. });  
  24. }  

Answers (3)