@zedux/react
Version:
A Molecular State Engine for React
53 lines (52 loc) • 2.59 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAtomContext = void 0;
const atoms_1 = require("@zedux/atoms");
const core_1 = require("@zedux/core");
const react_1 = require("react");
const useEcosystem_1 = require("./useEcosystem");
const utils_1 = require("../utils");
/**
* A React hook that accepts an atom template and returns an atom instance of
* that template that has been provided over React context via `<AtomProvider>`
* in a parent component.
*
* By default, returns undefined if no atom instance was provided.
*
* Pass an array of atom params (or an empty array if the atom doesn't take
* params) as the second argument to make Zedux find or create the atom instance
* matching the passed params if no atom instance was provided.
*
* Pass `true` as the second argument to make Zedux throw an error if no atom
* instance was provided. This is the recommended overload in almost all
* situations.
*
* If the provided atom instance is Destroyed, this hook logs an error but
* returns the Destroyed instance as-is. Most other Zedux APIs are able to
* recover from being passed a Destroyed instance by finding and using a new,
* non-Destroyed version of the instance. You should still fix the problem as it
* represents a memory leak.
*
* It can be fixed by simply using `useAtomInstance()` to get the atom instance
* in the providing component.
*/
const useAtomContext = (template, defaultParams) => {
const ecosystem = (0, useEcosystem_1.useEcosystem)();
const instance = (0, react_1.useContext)((0, utils_1.getReactContext)(ecosystem, template));
if (!defaultParams || (0, core_1.is)(instance, atoms_1.AtomInstanceBase)) {
if (true /* DEV */ && (instance === null || instance === void 0 ? void 0 : instance.status) === 'Destroyed') {
console.error(`Zedux: useAtomContext - A destroyed atom instance was provided with key "${instance.id}". This is not recommended. Provide an active atom instance instead e.g. by calling \`useAtomInstance()\` in the providing component.`);
}
return instance;
}
if (defaultParams === true) {
if (true /* DEV */) {
throw new ReferenceError(`Zedux: useAtomContext - No atom instance was provided for atom "${template.key}".`);
}
// TODO: this should probably still throw an error. Change this when we have
// a decent system for minified prod errors
return instance;
}
return ecosystem.getInstance(template, defaultParams);
};
exports.useAtomContext = useAtomContext;
;