Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

loadFromSessionStorage

Loads and parses a value from sessionStorage by key.

TypeScript
Copied!
1/**
2 * Loads and parses a value from sessionStorage by key.
3 *
4 * @param key - The sessionStorage 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 loadFromSessionStorage<T>(key: string, fallback?: T): T | undefined {
10  try {
11    const item = sessionStorage.getItem(key);
12    if (item === null) return fallback;
13    return JSON.parse(item) as T;
14  } catch (err) {
15    console.warn(`[loadFromSessionStorage] Failed to parse key "${key}":`, err);
16    if (fallback !== undefined) return fallback;
17    throw err;
18  }
19}
  • Safe JSON Parsing with Fallback

    Prevents application crashes by falling back to a default value if parsing fails or key is absent.

  • Typed Return Support

    Uses generics (<T>) to allow typed access to parsed data, improving TypeScript developer experience.

  • Error Transparency

    Logs detailed warnings for malformed JSON, aiding debugging and data integrity checks.

  • Session-Based Persistence

    Retrieves temporary data scoped to the browser session, ideal for sensitive or short-lived values.

Tests | Examples

TypeScript
Copied!
1const key = 'testKey';
2
3beforeEach(() => {
4  sessionStorage.clear();
5  jest.spyOn(console, 'error').mockImplementation(() => {});
6});
7
8afterEach(() => {
9  jest.restoreAllMocks();
10});
11
12test('returns parsed value from sessionStorage', () => {
13  sessionStorage.setItem(key, JSON.stringify({ a: 1 }));
14  expect(loadFromSessionStorage(key)).toEqual({ a: 1 });
15});
16
17test('returns fallback when key not found', () => {
18  expect(loadFromSessionStorage('missingKey', 'fallback')).toBe('fallback');
19});
20
21test('returns fallback on parse error if fallback provided', () => {
22  sessionStorage.setItem(key, 'not json');
23  expect(loadFromSessionStorage(key, 'fallback')).toBe('fallback');
24});
25
26test('throws on parse error when fallback not provided', () => {
27  sessionStorage.setItem(key, 'not json');
28  expect(() => loadFromSessionStorage(key)).toThrow();
29  expect(console.error).toHaveBeenCalledWith(
30    expect.stringMatching(/Failed to load/),
31    expect.anything()
32  );
33});

Common Use Cases

  • Restoring UI State

    Reload UI selections, filters, or tab states that were stored during the session.

  • Retaining Wizard/Flow Progress

    Resume a step-based process without restarting from the beginning after page refresh.

  • Accessing Session Cache

    Retrieve cached API results or temporary user input saved earlier in the session.

  • Fallback Recovery

    Gracefully handle missing or corrupt sessionStorage entries with user-defined defaults.

  • Testing or Debugging

    Load session-persisted test data or diagnostics tools configurations.

Codebase: Utilities -> Storage -> loadFromSessionStorage | Yevhen Klymentiev