How to save an object to localStorage
Short answer
localStorage stores only strings. Convert an object to JSON when saving and back when reading:
const settings = { theme: 'dark', fontSize: 16 };
localStorage.setItem('settings', JSON.stringify(settings));
const saved = JSON.parse(localStorage.getItem('settings'));A default value
If there is no key yet, getItem() returns null. A broken value may also be stored there. A helper handles both cases:
function load(key, fallback) {
try {
const value = localStorage.getItem(key);
return value === null ? fallback : JSON.parse(value);
} catch {
return fallback;
}
}
const cart = load('cart', []);Removing
removeItem() deletes one key, clear() deletes everything stored by the site:
localStorage.removeItem('cart');Common mistake
Without JSON.stringify() an object turns into the useless string [object Object]:
localStorage.setItem('user', { name: 'Anna' });
localStorage.getItem('user'); // '[object Object]'Functions used in this recipe
- JSON.stringify — Converts a value to a JSON string.
- JSON.parse — Parses a JSON string and returns the value.