loadFromLocalStorage
Loads and parses a value from localStorage by key.
1/**
2 * Loads and parses a value from localStorage by key.
3 *
4 * @param key - The localStorage key to load.
5 * @param fallback - A fallback value if parsing fails or key is missing.
6 * @returns The parsed value or the fallback.
7 * @throws Error if JSON parsing fails and no fallback is provided.
8 */
9export function loadFromLocalStorage<T>(key: string, fallback?: T): T | undefined {
10 try {
11 const item = localStorage.getItem(key);
12 if (item === null) return fallback;
13 return JSON.parse(item) as T;
14 } catch (err) {
15 console.warn(`[loadFromLocalStorage] Failed to parse key "${key}":`, err);
16 if (fallback !== undefined) return fallback;
17 throw err;
18 }
19}
Safe Parsing with Fallback Support
Gracefully handles missing or malformed data by optionally returning a fallback value, preventing runtime errors.
Typed Return Value
Utilizes generics to maintain type safety, making it easier to work with the returned value in TypeScript projects.
Minimal Logging for Debugging
Warns developers when parsing fails, aiding in identifying corrupted or incompatible data.
Flexible Error Handling
Developers can choose between strict mode (no fallback) or tolerant mode (with fallback), depending on application needs.
Tests | Examples
1const key = 'testKey';
2
3beforeEach(() => {
4 localStorage.clear();
5 jest.spyOn(console, 'error').mockImplementation(() => {});
6});
7
8afterEach(() => {
9 jest.restoreAllMocks();
10});
11
12test('returns parsed value from localStorage', () => {
13 localStorage.setItem(key, JSON.stringify({ a: 1 }));
14 expect(loadFromLocalStorage(key)).toEqual({ a: 1 });
15});
16
17test('returns fallback when key not found', () => {
18 expect(loadFromLocalStorage('missingKey', 'fallback')).toBe('fallback');
19});
20
21test('returns fallback on parse error if fallback provided', () => {
22 localStorage.setItem(key, 'not json');
23 expect(loadFromLocalStorage(key, 'fallback')).toBe('fallback');
24});
25
26test('throws on parse error when fallback not provided', () => {
27 localStorage.setItem(key, 'not json');
28 expect(() => loadFromLocalStorage(key)).toThrow();
29 expect(console.error).toHaveBeenCalledWith(
30 expect.stringMatching(/Failed to load/),
31 expect.anything()
32 );
33});
Common Use Cases
Restoring User Preferences
Load saved settings like theme, locale, or sidebar state after page reloads.
Reading Cached API Results
Retrieve previously fetched data to display instantly while waiting for fresh responses.
State Rehydration in SPAs
Recover application state (e.g., cart contents, recent views) after a full reload or tab revisit.
Loading Feature Flags
Access persisted flags or A/B test values stored in localStorage for early logic branching.