Explain Codes LogoExplain Codes Logo

How to store objects in HTML5 localStorage/sessionStorage

javascript
localstorage
sessionstorage
json-stringification
Nikita BarsukovbyNikita Barsukov·Sep 20, 2024
TLDR

Before storing objects in localStorage or sessionStorage, utilize JSON.stringify() to convert them to strings. For fetching them back, JSON.parse() comes to your rescue:

const obj = {name: 'Doe', age: 42}; // They say age is just a number. But not in localStorage. It's a string here. localStorage.setItem('user', JSON.stringify(obj)); const user = JSON.parse(localStorage.getItem('user'));

Remember, both localStorage and sessionStorage can only store strings. So when the need comes to save or retrieve objects, convert them using the above methods.

Saving objects made easy

Living with a string limit? Convert objects to strings and vice versa by extending the Storage.prototype:

Storage.prototype.setObject = function(key, value) { // Gson. Json. It's not a typo. It's evolution. this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { const value = this.getItem(key); // Some say JSON.parse can beat Inception in dream parsing. return value && JSON.parse(value); }; const user = { name: 'Doe', age: 42 }; // Meet JSON, the object shrinker. localStorage.setObject('user', user); // Knock knock. Who's there? Your object! const retrievedUser = localStorage.getObject('user');

This form of encapsulation provides an intuitive syntax when storing and fetching objects from localStorage.

Dealing with non-serializable values

Let's not forget about the non-serializable values. JSON.stringify() can handle a lot, but even it has its kryptonite:

const data = { date: new Date(), regex: /regex/ }; localStorage.setObject('data', { date: data.date.toISOString(), // My regex brings all the devs to the yard. regex: data.regex.toString() }); const retrievedData = localStorage.getObject('data'); retrievedData.date = new Date(retrievedData.date); // Spreading regex love, one parse at a time. retrievedData.regex = new RegExp(retrievedData.regex.slice(1, -1));

Handling potential pitfalls

Here be dragons, or so they say. To handle potential issues:

const safeGetObject = (key) => { const value = localStorage.getItem(key); // localStorage is like a box of chocolates. You never know what you're gonna get. return value ? JSON.parse(value) : null; };

When life gives you circular references, make lemonade with a replacer function in JSON.stringify(). Don't forget using object validation with typeof.

Type matters

Different data types, different methods. When parsing the stored data:

  • Booleans: Check using 'true' or 'false'
  • Numbers: Convert them using parseFloat()
  • Dates: Convert stored dates with new Date(parseInt(...))
  • RegExp: See the 'non-serializable values' section? We love regex!

And a tip straight from Captain Obvious: Stay informed about the specification updates!