Last active
January 3, 2023 07:37
-
-
Save Gerhut/e93c828c1ff041aa0fedd19c742dde3a to your computer and use it in GitHub Desktop.
recoil atom with sync effects
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 { | |
atom, | |
atomFamily, | |
AtomFamilyOptions, | |
AtomOptions, | |
ReadWriteSelectorFamilyOptions, | |
ReadWriteSelectorOptions, | |
selector, | |
selectorFamily, | |
SerializableParam | |
} from 'recoil' | |
export function atomWithEffect<T>(options: AtomOptions<T>, effect: ReadWriteSelectorOptions<T>['set']) { | |
const _atom = atom<T>(options) | |
return selector<T>({ | |
key: options.key + '__proxy', | |
get: ({ get }) => get(_atom), | |
set: (helpers, newValue) => { | |
helpers.set(_atom, newValue) | |
effect(helpers, newValue) | |
} | |
}) | |
} | |
export function atomFamilyWithEffect<T, P extends SerializableParam>( | |
options: AtomFamilyOptions<T, P>, | |
effect: ReadWriteSelectorFamilyOptions<T, P>['set'] | |
) { | |
const _atomFamily = atomFamily<T, P>(options) | |
return selectorFamily<T, P>({ | |
key: options.key + '__proxy', | |
get: (parameter) => { | |
const _atom = _atomFamily(parameter) | |
return ({ get }) => get(_atom) | |
}, | |
set: (parameter) => { | |
const _atom = _atomFamily(parameter) | |
const _effect = effect(parameter) | |
return (helpers, newValue) => { | |
helpers.set(_atom, newValue) | |
_effect(helpers, newValue) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment