Localstorage is a simple way to save user data on your website, by letting them save it to their browser. All it takes is a little JSON and you'll be on your way to a friendlier user experience.
Getting input
Once you've got some input from a user via Form or browsing data, You'll need to save that to the browser. Localstorage manages its storage based on a key value pair. So take the array or object your data is stored in, assign it to a variable, and stringify it with JSON. The save operation will look something like this
localStorage.setItem("keyAsAString", JSON.stringify(myDataObjOrArray));
You can decide when the localStorage should be updated, but generally, anytime the user resubmits a form or some kind of data, its a good idea to call this method again.
Retrieving values
When the user comes back to the page, check local storage for the data. Make sure to parse it using JSON or you will just get a string.
data = JSON.parse(localStorage.getItem("keyAsAString)) || []
It's very helpful to add a default if this fails, as I did in the above example.
That's all there is to localstorage. Where have you used this in a personal project?
Top comments (4)
Nice article.
But, be aware of consequences of using localStorage.clear() in any other app.
I'm unfamiliar with that command, does it clear ALL localstorage? or just the localstorage for the page. As far as I know, each webpage has a seperate localstorage.
It will clear your whole storage regardless of how toy stored the data.
Looks like you would be better off using
localStorage.removeItem("keyToRemove")
since it would only remove one item