DEV Community

Seth A Burleson
Seth A Burleson

Posted on

3 1

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?

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more