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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With