Storage Adapter
Automatically persist and restore store state to browser storage. State survives page refreshes and browser sessions.
Why Use This
- Automatic sync - Saves on every state change, restores on mount
- Selective persistence - Choose which keys to persist
- Validation - Validate stored data before restoring
- Storage choice - Use localStorage (persistent) or sessionStorage (tab-scoped)
Installation
npm
pnpm
yarn
npm install contection-storage-adapter
pnpm add contection-storage-adapter
yarn add contection-storage-adapter
Usage
import { createStorageAdapter } from "contection-storage-adapter";
const storageAdapter = createStorageAdapter({
storage: localStorage,
keys: ["theme", "user"],
});
storageAdapter.attach(AppStore);
Options
| Option | Type | Description |
|---|---|---|
storage | Storage | localStorage or sessionStorage |
keys | string[] | Store keys to persist |
validate | (data) => boolean | Validate before restoring |
storageKey | string | Custom storage key name |
With Validation
const storageAdapter = createStorageAdapter({
storage: localStorage,
keys: ["theme", "settings"],
validate: (data) => {
if (data.theme && !["light", "dark"].includes(data.theme)) {
return false;
}
return true;
},
});
Session Storage
// Data cleared when tab closes
const sessionAdapter = createStorageAdapter({
storage: sessionStorage,
keys: ["formData"],
});
Examples
- nextjs-bsky - Combined with cookie adapter
- react-routerjs-bsky - React Router integration