jotai-effect
Version:
41 lines • 1.94 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.withAtomEffect = withAtomEffect;
const internals_1 = require("jotai/vanilla/internals");
const atomEffect_1 = require("./atomEffect.js");
const env_1 = require("./env.js");
function withAtomEffect(targetAtom, effect) {
const effectAtom = (0, atomEffect_1.atomEffect)((get, set) => {
const getter = ((a) => a === targetWithEffect ? get(targetAtom) : get(a));
getter.peek = get.peek;
return targetWithEffect.effect.call(targetAtom, getter, set);
});
if ((0, env_1.isDev)()) {
Object.defineProperty(effectAtom, 'debugLabel', {
get: () => { var _a; return `${(_a = targetWithEffect.debugLabel) !== null && _a !== void 0 ? _a : '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 = (0, internals_1.INTERNAL_getBuildingBlocksRev1)(store);
const storeHooks = (0, internals_1.INTERNAL_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
;