Created
December 22, 2020 19:55
-
-
Save plusgut/0358b24992adf036e8980bb6b3f6bedb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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