Skip to content

Instantly share code, notes, and snippets.

@zerobias
Created August 26, 2018 17:38
Show Gist options
  • Save zerobias/7dd4799d3877d0ee1e690f210de4576c to your computer and use it in GitHub Desktop.
Save zerobias/7dd4799d3877d0ee1e690f210de4576c to your computer and use it in GitHub Desktop.
effector persistent store
//@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