Storage presets
Four presets that each remove an argument from every call site.
createLocalStorage<T>(options?): StorageInstance<T>
createSessionStorage<T>(options?): StorageInstance<T>
createUrlSearchParamsStorage<T>(options?): StorageInstance<T>
createUrlSearchParamsInHashStorage<T>(options?): StorageInstance<T>Their options are createStorage()'s without provider — the preset supplies it. The two URL presets also take push.
Usage
import {
createLocalStorage,
createSessionStorage,
createUrlSearchParamsInHashStorage,
createUrlSearchParamsStorage,
} from '@studiometa/js-toolkit';
interface Prefs {
theme: 'light' | 'dark';
}
createLocalStorage<Prefs>({ prefix: 'app:' });
createSessionStorage<Prefs>();
createUrlSearchParamsStorage<Prefs>({ push: true });
createUrlSearchParamsInHashStorage<Prefs>();push
The two URL presets choose history.pushState over the default replaceState:
push | Each write |
|---|---|
false | replaces the current entry |
true | adds a history entry |
true is what makes a filter state navigable with the back button. false is what keeps a scroll position or a tab index out of the history.
Which URL preset
| Preset | Reads and writes | Survives |
|---|---|---|
createUrlSearchParamsStorage() | location.search | a share, a bookmark, the server |
createUrlSearchParamsInHashStorage() | location.hash, as params | a share and a bookmark, never the server |
Both rebuild the whole location on each write, so a search write keeps the hash and a hash write keeps the query string.
Why only these four
A factory exists only where its product has state. These four each replace an argument at every call site, which is worth an export. createLocalStorageProvider() and createSessionStorageProvider() are removed — the instances say the same thing with nothing to call.
See Providers.