Explain Codes LogoExplain Codes Logo

How do I store an array in localStorage?

javascript
localstorage
utility-functions
error-handling
Anton ShumikhinbyAnton ShumikhinΒ·Nov 2, 2024
⚑TLDR

In a nutshell, you need to convert your array into a string using JSON.stringify before storing it in localStorage. To retrieve it, use JSON.parse to convert the stored string back into an array.

// A tasty array of fruits localStorage.setItem('fruits', JSON.stringify(['🍏', '🍌', 'πŸ’'])); // Fruit salad time! let fruits = JSON.parse(localStorage.getItem('fruits'));

Enhancing localStorage with utility functions

Roll your own setObj and getObj methods

You can introduce custom setObj and getObj methods on the Storage object to simplify storing and retrieving non-string data types.

// Adding some handy utility tools to our toolkit. Storage.prototype.setObj = function(key, obj) { this.setItem(key, JSON.stringify(obj)); }; Storage.prototype.getObj = function(key) { return JSON.parse(this.getItem(key)); };

Using structured keys for nested data storage

Handling complex data? Emulate nested storage by creating keys that resemble object dot notation. This way, you can retrieve and store data in an organized manner.

// Saving user's theme settings localStorage.setObj('user.settings.theme', { color: 'blue', font: 'Arial' }); // Extract user's theme settings let themeSettings = localStorage.getObj('user.settings.theme');

Can't forget about IE7...

To ensure compatibility with older browsers like Internet Explorer 7, incorporate json2.js which provides a consistent API for JSON.stringify and JSON.parse.

<!--[if IE 7]> <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.js"></script> <![endif]-->

Special precautions and potential pitfall

Be mindful that localStorage, as its name suggests, only stores data as strings. Therefore, handling special characters and large amounts of data can require special care:

  • Keep it simple. Use catchy keys: Even though localStorage.keyName can offer a quick shorthand for setItem and getItem, it's better to stick to full methods for clarity.

  • Guard against special characters: Utilize JSON.stringify to prevent special characters in arrays from causing issues, like beating the dragon in your favorite game!

  • Beware of localStorage limits: Typically, you have around 5MBβ€”enough to store "War and Peace" but not the entire Library of Congress. So, if you store large arrays, you might run out of space!

Pro tips for localStorage maniacs

Explore these additional tips, tricks, and considerations for mastering the localStorage game:

Structuring your data

Avoid flat designs and use meaningful keys to create organized storage that simulates your data's structure just like a 🐿️ does with its food.

Graceful error handling

Include error handling for situations where localStorage might be choked up or acting snobbish (i.e., full or restricted):

try { localStorage.setObj('fruits', ['🍏', '🍌', 'πŸ’']); } catch(e) { if(e === QUOTA_EXCEEDED_ERR){ console.error('🧨 BOOM! Quota exceeded, you have too many fruits in your basket!'); // Data wasn't successfully saved due to quota exceed so throw an error } }

Clean-up operations

Regular cleanup is essential to keep localStorage operating at optimal conditions, like a well-oiled machine:

localStorage.removeItem('unusedDataKey'); // Out with the old, in with the new!