How to store objects in HTML5 localStorage/sessionStorage
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:
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:
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:
Handling potential pitfalls
Here be dragons, or so they say. To handle potential issues:
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!
Was this article helpful?