@zedux/atoms
Version:
A Molecular State Engine for React
41 lines (40 loc) • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectAtomInstance = void 0;
const createInjector_1 = require("../factories/createInjector");
const index_1 = require("../utils/index");
const defaultOperation = 'injectAtomInstance';
/**
* injectAtomInstance
*
* Creates an atom instance for the passed atom based on the passed params. If
* an instance has already been created for the passed params, reuses the
* existing instance.
*
* Registers a static graph dependency on the atom instance. This means atoms
* that use this injector will *not* reevaluate when this atom instance's state
* changes.
*
* Pass false as the 4th param to prevent this graph dependency from being
* registered. Useful when you need to control the graph dependency manually.
* `injectAtomSelector` does this internally.
*
* @param atom The atom to instantiate or reuse an instantiation of.
* @param params The params for generating the instance's key.
* @param operation The operation name (e.g. name of the injector function)
* that's triggering this graph dependency. If you're using this injector
* directly in an atom, it's fine to omit this parameter.
* @returns An atom instance, keyed based on the passed params.
*/
exports.injectAtomInstance = (0, createInjector_1.createInjector)(defaultOperation, (instance, atom, params, config) => {
const injectedInstance = instance.ecosystem._evaluationStack.atomGetters.getInstance(atom, params, [(config === null || config === void 0 ? void 0 : config.subscribe) ? 0 : index_1.Static, (config === null || config === void 0 ? void 0 : config.operation) || defaultOperation]);
return {
result: injectedInstance,
type: `${index_1.prefix}/atom`,
};
}, (prevDescriptor, instance, atom, params, config) => {
// make sure the dependency gets registered for this evaluation
const injectedInstance = instance.ecosystem._evaluationStack.atomGetters.getInstance(atom, params, [(config === null || config === void 0 ? void 0 : config.subscribe) ? 0 : index_1.Static, (config === null || config === void 0 ? void 0 : config.operation) || defaultOperation]);
prevDescriptor.result = injectedInstance;
return prevDescriptor;
});