UNPKG

@zedux/atoms

Version:

A Molecular State Engine for React

38 lines (37 loc) 2.1 kB
import { createInjector } from '../factories/createInjector.js'; import { prefix, Static } from '../utils/index.js'; 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. */ export const injectAtomInstance = 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 : Static, (config === null || config === void 0 ? void 0 : config.operation) || defaultOperation]); return { result: injectedInstance, type: `${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 : Static, (config === null || config === void 0 ? void 0 : config.operation) || defaultOperation]); prevDescriptor.result = injectedInstance; return prevDescriptor; });