Skip to content

Instantly share code, notes, and snippets.

@NoriSte
Last active October 15, 2020 06:51
Show Gist options
  • Save NoriSte/8ec8bf8e4487edaee0a1914f56c25070 to your computer and use it in GitHub Desktop.
Save NoriSte/8ec8bf8e4487edaee0a1914f56c25070 to your computer and use it in GitHub Desktop.
Re-implementing Recoil APIs / article gists
// @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