Argument of type 'any[]' is not assignable to parameter of type 'string'

I am trying to set the items array and push to localStorage with the following code:

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

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

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

I get the following errors:

Argument of type ‘any’ is not assignable to parameter of type ‘string’.

for localStorage.setItem(this.items, JSON.stringify(data));

Argument of type ‘{ thumbnail: any; quantity: any; product_name: any; product_price: any; }’ is not assignable to parameter of type ‘string’.

for this.items.push(JSON.parse(localStorage.getItem(data)));

In my HTML:

<tr *ngFor="let item of items;">
<td>
<td><img src="../assets/images/gallery/{{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>

Are you using Typescript for this project? If so, this problem is caused because there is incompatible types that you are trying to pass in to a method or function. It looks like you’re trying to set items that from the error telling me that it’s an array and you’re trying to set it as a local storage variable name.

Snigo has explained it better than me below ↓

1 Like

setItem() expects string as a key and you’re passing any[] (which by itself already an error, just silent). Looking at the next line it seems you swapped things around and forgot quotes on data:

localStorage.setItem('data', JSON.stringify(this.items));
this.items.push(JSON.parse(localStorage.getItem('data'))); // HEADS UP!!! THIS MIGHT BITE!!!

Blindly pushing cached data to items is something I would think twice about if I were you. Good luck!

2 Likes