Skip to content

Instantly share code, notes, and snippets.

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