Storing and retrieving Objects in HTML5 localStorage

If you are building an application that requires some in-browser storage, there’s a high probability you will end up using localStorage API.

Unfortunately, the API itself is not built for more complex use-cases or to say, non-primitive values, like objects, arrays etc. Luckily, we can do “serialization” and “deserialization” of our data, store it as a string and parse it back to JSON when we retrieve it.

const alien = { name: 'Kikki', age: 8244, origin: 'unknown' };
window.localStorage.setItem('alien', JSON.stringify(alien));

// if you do localStorage.alien in your developer console you will get a string back

"{"name":"Kikki","age":8244,"origin":"unknown"}"

As you can see, our object is a string and we obviously can’t operate on it as if it was an object until we parse it back to JSON.

JSON.parse(localStorage.getItem('alien'));

// if you type this out in your console, you will get an alien object in return

Setting and Getting an object from localStorage

Of course, what we want to do with those implementations is turn them into functions. It would be silly to go around your whole project typing this madness. Since I’m using ES6, I can write out those functions in one line, implicitly returning functions. You can write them out it any way you want, the emphasis is on stringification and parsing.

 const setStorage = (key, value) => localStorage.setItem(key, JSON.stringify(value));
 const getStorage = (key) => JSON.parse(localStorage.getItem(key));

There we go. We have two handy functions we can reuse across our project(s). I usually have a utils.js file in every project holding utility functions like those.

Checking if localStorage is supported

Before we round up, I’ll also show you a handy way to check if localStorage API is suppored on a given device. I didn’t come up with this solution but I found it as part of Modernizr library.

const hasStorage = () => {
  const test = 'test';
  try {
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch (e) {
    return false;
  }
};

While in my opinion not incredibly beautiful, function is wrapped inside a try/catch block which ensures us that if the operations fails, error will be handled accordingly, in this case, we are simply returning false.

Well done, champion! In this one, you’ve learned more about localStorage, how to check its support and also how to store and retrieve non-primitive values.