Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will I use localStorage with Object

Please can someone make it clear why i need to do JSON.stringify(localStorage.setItem('data')); and then use JSON.parse(localStorage.getItem('data')) before i can get back my data object.

like image 605
Lekens Avatar asked Mar 09 '23 14:03

Lekens


1 Answers

In short: Because local storage can only store strings.

The longer answer is that Objects are complex data structures which, under the hood, consist of references to different parts of the computer's memory. You can't just dump them to a storage area because the data won't exist at those parts of the memory when you read the data back.

Thus you need to serialise the data somehow.

The localStorage API could have been written to do this automatically, but only under some circumstances. It wasn't, you have to do it manually, which means you are forced to know what you are doing so that (a) if you lose data it isn't due to the localStorage API being weird and mysterious and (b) you can choose between being memory efficient (localStorage gives you limited space) and being simple (just using JSON.stringify).

like image 191
Quentin Avatar answered Mar 21 '23 06:03

Quentin