Created
July 31, 2021 17:07
-
-
Save noizbuster/2eec8968f41be6377de61ebf30378fb7 to your computer and use it in GitHub Desktop.
persistent recoil.js atom using local storage
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
import { atom, AtomEffect, AtomOptions, DefaultValue } from 'recoil'; | |
export const localStorageEffect = | |
(key: string): AtomEffect<any> => | |
({ setSelf, onSet }) => { | |
const savedValue = localStorage.getItem(key); | |
if (savedValue != null) { | |
setSelf(JSON.parse(savedValue)); | |
} | |
onSet((newValue) => { | |
if (newValue instanceof DefaultValue) { | |
localStorage.removeItem(key); | |
} else { | |
localStorage.setItem(key, JSON.stringify(newValue)); | |
} | |
}); | |
}; | |
export function localStorageAtom<T>(options: AtomOptions<T>) { | |
return atom({ | |
...options, | |
effects_UNSTABLE: [localStorageEffect(options.key)], | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment