user8770372
user8770372

Reputation:

Javascript Saving and retrieving array data to and from localstorage

I have an array which looks like this:

this.data = [
    { cols: 1, rows: 1, y: 0, x: 4 },
    { cols: 1, rows: 1, y: 2, x: 5 }
];

I am saving it to localstorage using:

localStorage.setItem('my_data', JSON.stringify(this.data));

I then retrieve it using:

this.data = JSON.parse( localStorage.getItem('my_data'));

This problem is that when I try to get the data I'm getting this error:

Type NULL is not assignable to Type String.

How can I fix this?

Upvotes: 1

Views: 273

Answers (1)

Fenton
Fenton

Reputation: 250932

To remove the type error (which is only shown with the strict stuff enabled), you can make sure that you handle nulls:

// Warning... don't use this code until you read the next section!
data = JSON.parse(localStorage.getItem('my_data') || '');

This is because localStorage.getItem can return string | null but JSON.parse only accepts string (i.e. not nulls).

Correct Code

If you also want your code to have a fair shot of working, my recommended solution would go a step further and supply a reasonably default JSON string:

data = JSON.parse(localStorage.getItem('my_data') || '[]');

Error Notes

The error in this question would only be visible with strictNullChecks enabled as this catches the potential null being assigned to string.

The exact error in this case would be:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

Upvotes: 1

Related Questions