Created
October 19, 2020 06:21
Re-implementing Recoil APIs / article gists
This file contains 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 | |
/** | |
* 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