Created
August 26, 2018 17:38
-
-
Save zerobias/7dd4799d3877d0ee1e690f210de4576c to your computer and use it in GitHub Desktop.
effector persistent store
This file contains hidden or 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
//@flow | |
import { | |
createStore, | |
createEffect, | |
type Store, | |
} from 'effector' | |
export function persistentStore(defaults: string, key: string) { | |
const readEff = createEffect(`read ${key}`) | |
const writeEff = createEffect(`write ${key}`) | |
readEff.use((_?: void) => { | |
try { | |
return localStorage.getItem(key) | |
} catch (error) { | |
return null | |
} | |
}) | |
writeEff.use((value: string | null) => { | |
try { | |
if (value == null) localStorage.removeItem(key) | |
else localStorage.setItem(key, value) | |
} catch (error) {} | |
}) | |
const store = createStore(defaults) | |
store | |
.on(readEff.done, (state, {result}) => result) | |
.on(writeEff, (_, upd: string | null) => upd) | |
return { | |
store, | |
write: writeEff, | |
read: readEff, | |
clear: writeEff.prepend((_?: void) => null), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment