LocalStorage Helper

v1.0.0

Typed JSON access to the browser localStorage API.

Set and get values

Values are serialized as JSON when stored and parsed when read. set() throws a TypeError before changing storage when the value cannot be represented as JSON, including undefined, functions, symbols, and values that make JSON.stringify() throw. If get() encounters malformed data written by another caller or an older application version, it removes that entry and returns null.

import { LocalStorageHelper } from '@oardi/ts-utils';

LocalStorageHelper.set('settings', { compact: true });

const settings = LocalStorageHelper.get<{ compact: boolean }>('settings');
// { compact: true }

get() returns null when the key does not exist.

Remove values

const removed = LocalStorageHelper.remove('settings');
// true when the key existed, otherwise false

Stored falsy values such as false, 0, an empty string, and null are removed correctly.

Find keys by prefix

LocalStorageHelper.set('app:theme', 'dark');
LocalStorageHelper.set('app:locale', 'en');

LocalStorageHelper.getKeysBy('app:');
// ['app:theme', 'app:locale']

Clear storage

LocalStorageHelper.removeAll();

removeAll() clears the complete localStorage area for the current origin, including keys that were not created through this helper.

Previous:Helpers

← Image Helper

Next:Helpers

Logger Helper →