DEV Community

Seth A Burleson
Seth A Burleson

Posted on

Using LocalStorage to improve your webpage

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));
Enter fullscreen mode Exit fullscreen mode

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)) || []
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
sudarshansb143 profile image
sudarshan

Nice article.

But, be aware of consequences of using localStorage.clear() in any other app.

Collapse
 
sbrevolution5 profile image
Seth A Burleson

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.

Collapse
 
sudarshansb143 profile image
sudarshan

It will clear your whole storage regardless of how toy stored the data.

Thread Thread
 
sbrevolution5 profile image
Seth A Burleson

Looks like you would be better off using localStorage.removeItem("keyToRemove") since it would only remove one item