Skip to content

Instantly share code, notes, and snippets.

@plusgut
Created December 22, 2020 19:55
Show Gist options
  • Save plusgut/0358b24992adf036e8980bb6b3f6bedb to your computer and use it in GitHub Desktop.
Save plusgut/0358b24992adf036e8980bb6b3f6bedb to your computer and use it in GitHub Desktop.
import { Store } from "@plusnew/core";
export default function <T, U extends Store<T, any>>(
key: string,
initialValue: T,
callback: (value: T) => U
): U {
const result = localStorage.getItem(key);
let store: U;
if (result === null) {
store = callback(initialValue);
} else {
store = callback(JSON.parse(result));
}
store.subscribe(() =>
localStorage.setItem(key, JSON.stringify(store.getState()))
);
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment