Last active
October 15, 2020 06:51
-
-
Save NoriSte/8ec8bf8e4487edaee0a1914f56c25070 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 | |
/** | |
* Get the current Recoil Atom' value | |
*/ | |
const coreGetAtomValue = <T>(recoilId: string, atom: Atom<T>): T => { | |
const coreRecoilValue = getRecoilStore(recoilId)[atom.key]; | |
// type-safety | |
if (coreRecoilValue.type !== "atom") { | |
throw new Error(`${coreRecoilValue.key} is not an atom`); | |
} | |
return (coreRecoilValue.value as any) as T; | |
}; | |
/** | |
* Get the current Recoil Selector' value | |
*/ | |
const coreGetSelectorValue = <T>(recoilId: string, selector: Selector<T>): T => | |
selector.get({ get: createPublicGetRecoilValue(recoilId) }); | |
/** | |
* Get the current Recoil Value' value | |
*/ | |
export const coreGetRecoilValue = <T>( | |
recoilId: string, | |
recoilValue: RecoilValue<T> | |
): T => | |
isAtom(recoilValue) | |
? coreGetAtomValue(recoilId, recoilValue) | |
: coreGetSelectorValue(recoilId, recoilValue); | |
/** | |
* Create a function that get the current Recoil Value' value | |
* @private | |
*/ | |
export const createPublicGetRecoilValue = <T>(recoilId: string) => ( | |
recoilValue: RecoilValue<T> | |
): T => coreGetRecoilValue(recoilId, recoilValue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment