Lockr: LocalStorage Wrapper

0.9.0-beta.2 · active · verified Wed Apr 22

Lockr is an extremely lightweight JavaScript library (<2KB minified) designed to simplify interactions with the browser's `localStorage` API. It provides a Redis-like API for storing various data types, including strings, numbers, objects, and arrays, and offers set-like operations (e.g., `sadd`, `smembers`, `sismember`, `srem`). It is currently in a beta phase, with version 0.9.0-beta.2, indicating ongoing development. While no explicit release cadence is stated, the active development and beta tag suggest regular updates towards a stable release. Its primary differentiator is its automatic object serialization/deserialization and its distinct Redis-inspired API for managing collections, moving beyond the simple key-value string storage of native `localStorage` and offering a more feature-rich experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting a key prefix, storing various data types (strings, numbers, objects, arrays), retrieving them, performing set-like operations, and removing keys.

import Lockr from 'lockr';

// Set a prefix for all keys (optional, but good practice)
Lockr.prefix = 'my_app_data_';

// Store various data types. Lockr automatically serializes objects and arrays.
Lockr.set('username', 'Alice Smith');
Lockr.set('userId', 42);
Lockr.set('settings', { theme: 'dark', notifications: true });
Lockr.set('favoriteFruits', ['apple', 'banana', 'cherry']);

// Retrieve values. Lockr automatically deserializes them.
console.log('Username:', Lockr.get('username'));
// Expected: Username: Alice Smith

console.log('Settings:', Lockr.get('settings'));
// Expected: Settings: { theme: 'dark', notifications: true }

// Use Redis-like set operations (sadd, smembers)
Lockr.sadd('uniqueTags', 'javascript');
Lockr.sadd('uniqueTags', 'typescript');
Lockr.sadd('uniqueTags', 'javascript'); // Adding again has no effect

console.log('Unique Tags:', Lockr.smembers('uniqueTags'));
// Expected: Unique Tags: [ 'javascript', 'typescript' ]

// Remove a key
Lockr.rm('username');
console.log('Username after removal:', Lockr.get('username', 'Guest'));
// Expected: Username after removal: Guest (demonstrating default value)

// Get all values (only prefixed ones if prefix is set)
console.log('All stored values:', Lockr.getAll());

view raw JSON →