Skip to content

Instantly share code, notes, and snippets.

@noizbuster
Created July 31, 2021 17:07
Show Gist options
  • Save noizbuster/2eec8968f41be6377de61ebf30378fb7 to your computer and use it in GitHub Desktop.
Save noizbuster/2eec8968f41be6377de61ebf30378fb7 to your computer and use it in GitHub Desktop.
persistent recoil.js atom using local storage
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