Last active
October 19, 2020 06:15
-
-
Save NoriSte/96647da462a42172c838bfdd7bcef31e to your computer and use it in GitHub Desktop.
Re-implementing Recoil APIs / article gists
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
// @see https://github.com/NoriSte/recoil-apis | |
/** | |
* Provide a Recoil Value setter | |
* @private | |
*/ | |
const coreSetRecoilValue = <T>( | |
recoilId: string, | |
recoilValue: RecoilValue<T>, | |
nextValue: T | |
) => { | |
if (isAtom(recoilValue)) { | |
coreSetAtomValue(recoilId, recoilValue, nextValue); | |
} else if (recoilValue.set) { | |
recoilValue.set( | |
{ | |
get: createPublicGetRecoilValue(recoilId), | |
set: createPublicSetRecoilValue(recoilId) | |
}, | |
nextValue | |
); | |
} | |
}; | |
/** | |
* Set the Recoil Atom and notify the subscribers without passing the recoil id | |
*/ | |
const coreSetAtomValue = <T>( | |
recoilId: string, | |
recoilValue: RecoilValue<T>, | |
nextValue: T | |
) => { | |
const coreRecoilValue = getRecoilStore(recoilId)[recoilValue.key]; | |
if (coreRecoilValue.type !== "atom") { | |
throw new Error(`${coreRecoilValue.key} is not an atom`); | |
} | |
if (nextValue !== coreRecoilValue.value) { | |
coreRecoilValue.value = nextValue; | |
coreRecoilValue.subscribers.forEach((callback) => callback()); | |
} | |
}; | |
/** | |
* Create a function that provide a Recoil Value setter | |
* @private | |
*/ | |
export const createPublicSetRecoilValue = <T>(recoilId: string) => ( | |
recoilValue: RecoilValue<T>, | |
nextValue: T | |
) => coreSetRecoilValue(recoilId, recoilValue, nextValue); | |
/** | |
* Create a function that sets the Recoil Atom and notify the subscribers without passing the recoil id | |
* @private | |
*/ | |
export const createPublicSetAtomValue = <T>( | |
recoilId: string, | |
recoilValue: RecoilValue<T> | |
) => (nextValue: T) => coreSetAtomValue(recoilId, recoilValue, nextValue); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment