Skip to content

Instantly share code, notes, and snippets.

@NoriSte
Created October 19, 2020 06:21
Show Gist options
  • Save NoriSte/c30f3ac1bf73fc46c78d60e6b0db712c to your computer and use it in GitHub Desktop.
Save NoriSte/c30f3ac1bf73fc46c78d60e6b0db712c to your computer and use it in GitHub Desktop.
Re-implementing Recoil APIs / article gists
// @see https://github.com/NoriSte/recoil-apis
/**
* Register a new Recoil Value idempotently.
* @private
*/
export const registerRecoilValue = <T>(
recoilId: string,
recoilValue: RecoilValue<T>
) => {
const { key } = recoilValue;
const recoilStore = getRecoilStore(recoilId);
// the Recoil values must be registered at runtime because of the Recoil id
if (recoilStore[key]) {
return;
}
if (isAtom(recoilValue)) {
recoilStore[key] = {
type: "atom",
key,
default: recoilValue.default,
value: recoilValue.default,
subscribers: []
};
} else {
recoilStore[key] = {
type: "selector",
key,
subscribers: []
};
}
};
/**
* Subscribe to all the updates of a Recoil Value.
* @private
*/
export const subscribeToRecoilValueUpdates = (
recoilId: string,
key: string,
callback: Subscriber
) => {
const recoilValue = getRecoilStore(recoilId)[key];
const { subscribers } = recoilValue;
if (subscribers.includes(callback)) {
throw new Error("Already subscribed to Recoil Value");
}
subscribers.push(callback);
const unsubscribe = () => {
subscribers.splice(subscribers.indexOf(callback), 1);
};
return unsubscribe;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment