jotai-effect
Version:
38 lines • 1.78 kB
JavaScript
import { INTERNAL_getBuildingBlocksRev1 as getBuildingBlocks, INTERNAL_initializeStoreHooks as initializeStoreHooks, } from 'jotai/vanilla/internals';
import { atomEffect } from './atomEffect.js';
import { isDev } from './env.js';
export function withAtomEffect(targetAtom, effect) {
const effectAtom = atomEffect((get, set) => {
const getter = ((a) => a === targetWithEffect ? get(targetAtom) : get(a));
getter.peek = get.peek;
return targetWithEffect.effect.call(targetAtom, getter, set);
});
if (isDev()) {
Object.defineProperty(effectAtom, 'debugLabel', {
get: () => `${targetWithEffect.debugLabel ?? 'atomWithEffect'}:effect`,
});
effectAtom.debugPrivate = true;
}
const descriptors = Object.getOwnPropertyDescriptors(targetAtom);
descriptors.read.value = targetAtom.read.bind(targetAtom);
if ('write' in targetAtom && typeof targetAtom.write === 'function') {
descriptors.write.value = targetAtom.write.bind(targetAtom);
}
// avoid reading `init` to preserve lazy initialization
const targetPrototype = Object.getPrototypeOf(targetAtom);
const targetWithEffect = Object.create(targetPrototype, descriptors);
targetWithEffect.unstable_onInit = (store) => {
const buildingBlocks = getBuildingBlocks(store);
const storeHooks = initializeStoreHooks(buildingBlocks[6]);
let unsub;
storeHooks.m.add(targetWithEffect, function mountEffect() {
unsub = store.sub(effectAtom, () => { });
});
storeHooks.u.add(targetWithEffect, function unmountEffect() {
unsub();
});
};
targetWithEffect.effect = effect;
return targetWithEffect;
}
//# sourceMappingURL=withAtomEffect.js.map