Cannot read property 'storageKey' of undefined

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

storageKey = 'MyDataStorageKey';

public onSubmit(id, quantity, product_name){

var data = {
   id,
   quantity,
   product_name,
};
 
var retrieverObject = localStorage.getItem('items');
var retrieveObject = JSON.parse(retrieverObject);
this.items.push(data);

retrieveObject.forEach(function(el){
alert("This is the storage id " + el.id);
if (el.id == id){
alert(el.id + " same product");
} else {
alert("this id is not in storage ");
//error returns for the following line of code
localStorage.setItem(this.storageKey, JSON.stringify(this.items));
}
});
}

With a quick look, perhaps you need to have: let

let storageKey = ‘MyDataStorageKey’;

That throws the following error:

Unexpected token. A constructor, method, accessor, or property was expected.

Thanks anyway, ProgMan

I got the answer at another forum. Using the arrow function and putting this.items.push(data); in to the else condition fixed the problem!

The product still gets set after all even when localStorage is set. It’s not working as intended but the error message is suppressed.

<script>
//localStorage.removeItem('obj');
onSubmit=function(tis){
        var frm = tis;
	var ls=localStorage,obj,key,test=false;
	var data = {
   	id:null,
   	thumbnail:null,
   	quantity:null,
   	product_name:null,
   	product_price:null};
  	if(!ls.getItem('obj'))ls.setItem('obj',JSON.stringify([]));	
  	obj=JSON.parse(ls.getItem('obj'));	
	if(!frm.elements[0].value.length){alert("fill\nout\nID");return}	
	if(obj.length){
		for(var i=0;i<obj.length;i++)
			if(obj[i].id == frm.elements[0].value){
				update(obj[i]) ;
				return;	}}
	for(var i=0;i<frm.elements.length;i++)
		if(!frm.elements[i].value.length){alert("fill\nout\nform");return;}
	var cnt = 0;
	for(key in data)data[key]= frm.elements[cnt++].value;
	obj.push(data);	
	ls.setItem('obj',JSON.stringify(obj));	
	function update(arg){		
		if(!frm.elements[2].value){alert("fill\nin\nquantity");return}
		var q = +frm.elements[2].value;
		if (isNaN(q)){alert("fill in quantity\n with numeric");return}
		arg.quantity = Number(arg.quantity) + q;
		ls.setItem('obj',JSON.stringify(obj));}}
</script>
<form>
id<input><br>
thumbnail<input><br>
quantity<input><br>
product_name<input><br>
product_price<input><br>
<input type=button value=submit onclick=onSubmit(form);form.reset()>
</form>

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.

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

var data = {
   id,
   thumbnail,
   quantity,
   product_name,
   product_price
};

  var retrieverObject = localStorage.getItem('items');
  var retrieveObject = JSON.parse(retrieverObject);
 
retrieveObject.forEach(el => {
   if (el.id == id){
   this.quantity += quantity;
   } else {
   this.items.push(data);
   localStorage.setItem(this.storageKey, JSON.stringify(this.items));
   }
  });
}

Thanks, Da_vey, but I don’t want to use ids.

not a problem
I have removed the
id attributes

Thanks, Da_vey,but onSubmit takes 5 arguments not one:
onSubmit(id, thumbnail, quantity, product_name, product_price)

This is what my code looks like now:

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

var data = {
    id,
   thumbnail,
   quantity,
   product_name,
   product_price
};

var retrieverObject = localStorage.getItem('items');
    var retrieveObject = JSON.parse(retrieverObject)
  if (retrieverObject === null || retrieverObject === '[]' ) {
    this.items.push(data);
    localStorage.setItem(this.storageKey, JSON.stringify(this.items));
  } else {
    retrieveObject.forEach(el => {
  if (el.id == id && retrieverObject !== '[]' ){
        this.quantity += quantity;
      } else {
        this.items.push(data);
        localStorage.setItem(this.storageKey, JSON.stringify(this.items));
      }
    })    
 }
}

My code adds the product to the cart even if it’s already been added. It also doesn’t update the quantity like it should.

I have published my code at github: https://github.com/makamo66/angular-shopping-cart

Hey, Da_vey, I don’t need a solution now. My problem was solved at the stack overflow site.

The following code only works when I force it to reload at the end. How can I get the code to run without forcing it to reload?

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

this.product_price = parseFloat(product_price);


var data = {
    id,
   thumbnail,
   quantity,
   product_name,
   product_price
};
this.isSubmitted = true;

 // Get the saved stringified object from cache
const retrieverObject: string = localStorage.getItem(this.storageKey) || '';
// Parse it to an array, or set to a blank array, if there is no data
const retrieveObject: Array<any> = retrieverObject ? JSON.parse(retrieverObject) : [];
// Find the item from the array
let presentItem = retrieveObject.find(item => item.id === id);
// Update the data, if the item is found
if (presentItem) {
  //this.quantity += quantity;
  // If the stored objects quantity needs to be updated
  presentItem.quantity += quantity;
} else {
  // Else if not found in the saved array, push the new object
  retrieveObject.push(data);
}
// Set the new object to the same key
localStorage.setItem(this.storageKey, JSON.stringify(retrieveObject));
location.reload(true);
}

go to the developers window

find the localStorage area

copy what’s in there

paste it in a reply to this thread

Hi Da_vey. I have to go to work now. I will post it when I return tonight.

This problem was solved at https://stackoverflow.com/questions/63316140/dont-add-product-if-product-is-already-in-localstorage/63316931?noredirect=1#comment112041276_63316931

My localhost isn’t working any more. I shut down the McAfee firewall, re-started my computer and reverted back to the code that had worked before but my localhost still shows a blank page.