localStorage

Kevin Neyer
4 min readJan 16, 2021

--

Using JavaScript to implement the Web Storage API

Introduction

The last few weeks, I’ve been working on a code challenge that was required for an internship application. The challenge was to create a webpage that helped manage nominations for an award show. Users could search a database and nominate their favorite movies they feel should be up for nomination. When they’ve selected 5 nominees, they should be notified they’re finished.

After achieving the required deliverables, it was suggested to jazz it up a bit and add additional features or styling that best showcased our passions and skills. They gave a few for inspiration. One of which was saving the nominations if a user left the page.

I had implemented some additional features and styled how I saw fit. I had some time before the application deadline, so I thought it would be cool to figure out how to save the nominations list. Since this was a front-end application(the data base had been provided and all that was needed was an API key), and there were no auth or login features required, I was only working with my React app. My initial thought was, “I can only think of having these stored in a database that’s then called upon during page reopens or reloads”. I knew this was way out of bounds, giving the circumstances. After about a day racking my brain, it naturally occurred to me — “Can I use localStorage?”. I had only used localStorage when implementing auth and JWT tokens, so I wasn’t sure if it could be used in this capacity. A quick Google search, and, yes! I sure could.

Web Storage

As per MDN:

When writing code for the Web, there are a large number of Web APIs available. Web APIs are typically used with JavaScript, although this doesn’t always have to be the case.

One of these APIs is the Web Storage API. The Web Storage API —

provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

Web storage can be implemented in one of two ways: sessionStorage or localStorage. sessionStorage maintains a storage area that’s available for the duration of the page session. localStorage does the same thing but persists even after the browser is closed and reopened. Since I knew I needed it to persist after the browser is closed, localStorage was my choice.

localStorage

Setting Up

Invoking and creating localStorage will create an instance of the Storage object, through which data items can be set, retrieved and removed. To create a storage object, use the setItem method. It will take two arguments, a set of key/value pairs. Name the first what the key shall be called, and the second your value. In my application, I was using an array to hold my nominations state, so I knew this is what I needed my value to be. localStorage only supports strings as values, so we can use JSON.stringify to convert the array into strings.

Code featuring state and localStorage for nominations

Now, if I go into my Chrome Dev Tools, this should be accurately represented.

Chrome Dev Tools

Nice! There’s a key of nominations that points to a value of an empty array.

Adding To

Now that my localStorage exists, I need to add nominations to it. In my nominateHandler function(which adds a movie to the nomination state), I’ll add an additional line that also updates localStorage to reflect the updated state.

nominateHandler Function

Now when I add a movie, localStorage will reflect accordingly.

Chrome Dev Tools with Updated localStorage

There’s also a removeHandler that removes a nomination and updates state and localStorage using the same logic.

Putting It Together

While this will update localStorage, should the page be reopened or refreshed, my nominations list on the page won’t be accurately represented since my nominations useState hook is set to an empty array. Using conditional logic, this can be fixed.

Updated State Code

Here, a ternary operator is used to ask the questions “Does the nominations key in localStorage have any values, aka is it not an empty array? If so, set nominations state equal to the values stored in localStorage. If not, set state equal to an empty array”. Notice that to retrieve a value, the getItem method is used. Also notice that since JSON.stringify was used to convert the array to strings, JSON.parse is used to convert back to an array.

To tie everything together, I implemented the useEffect hook to load my nominations upon reload or reopen.

useEffect Hook to Load State

Conclusion

Using key/value pairs, localStorage stores data during page use and beyond. It has no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data. While not perfect for every situation, it useful for storing lists, carts, etc. in front end apps. Try it for yourself, and see if you can come up with some creative uses for web storage!

--

--