saveToSessionStorage
Saves a value to sessionStorage after serializing it to JSON.
1/**
2 * Saves a value to sessionStorage after serializing it to JSON.
3 *
4 * @param key - The key under which the value will be stored.
5 * @param value - The value to store (will be JSON-stringified).
6 */
7export function saveToSessionStorage<T>(key: string, value: T): void {
8 try {
9 const serialized = JSON.stringify(value);
10 sessionStorage.setItem(key, serialized);
11 } catch (e) {
12 console.error('Failed to save to sessionStorage:', e);
13 }
14}
Automatic Serialization
Converts any serializable value to JSON before saving, making it seamless to store complex data structures.
Scoped to Session
Data persists only for the duration of the browser session, which enhances security and privacy for temporary data.
Error-Resilient
Includes a try–catch block to handle serialization or storage errors without breaking the app.
Simple API Wrapper
Provides a consistent and minimal interface over the native
sessionStorage.setItem
, reducing boilerplate.
Tests | Examples
1beforeEach(() => {
2 sessionStorage.clear();
3 jest.clearAllMocks();
4});
5
6test('saveToSessionStorage - stores stringified value', () => {
7 saveToSessionStorage('user', { name: 'Alice' });
8 expect(sessionStorage.getItem('user')).toBe(JSON.stringify({ name: 'Alice' }));
9});
10
11test('saveToSessionStorage - handles primitive values', () => {
12 saveToSessionStorage('count', 5);
13 expect(sessionStorage.getItem('count')).toBe('5');
14});
15
16test('saveToSessionStorage - catches errors gracefully', () => {
17 const circular: any = {};
18 circular.self = circular;
19 const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
20 saveToSessionStorage('bad', circular);
21 expect(console.error).toHaveBeenCalled();
22});
Common Use Cases
Temporary Form State
Save user input that should persist across navigations within the same session but be discarded afterward.
Step-by-Step Wizards
Store progress in multi-step flows or modals that reset when the session ends.
Session-Limited User Data
Cache non-sensitive user data like filters, tab state, or UI preferences that shouldn't persist long-term.
Avoiding Redundant API Calls
Cache API responses during a session to reduce network traffic and latency.
Session-Specific Feature Flags
Store flags or toggles that are only relevant for the current user session.