UNPKG

mobx-store-provider

Version:
68 lines (67 loc) 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getStore = exports.useStore = exports.useCreateStore = exports.useProvider = void 0; const react_1 = require("react"); const stores = new Map(); /** * Register and/or retrieve a `store`. * @param identifier The identifier supplied by the consumer * @returns Store */ function retrieveStore(identifier) { if (!stores.has(identifier)) { const Context = (0, react_1.createContext)(null); Context.displayName = String(identifier); stores.set(identifier, { get provider() { return Context.Provider; }, get context() { return (0, react_1.useContext)(Context); }, }); } return stores.get(identifier); } /** * React Hook used to retrieve a store `Provider`. * @param model mobx-state-tree model * @param identifier The identifier used for the store (optional) * @returns The store Provider */ function useProvider(model, identifier) { return retrieveStore(arguments.length === 2 ? identifier : model) .provider; } exports.useProvider = useProvider; /** * React Hook used to instantiate a new store from within a component. * @param model mobx-state-tree model * @param snapshot input snapshot used during creation (optional) * @returns The store instance */ function useCreateStore(model, snapshot, env) { return (0, react_1.useMemo)(() => model.create(snapshot, env), []); } exports.useCreateStore = useCreateStore; /** * React Hook used to retrieve a store. * @param model mobx-state-tree model * @param identifier The identifier used for the store (optional) * @returns The store instance */ function useStore(model, identifier) { return arguments.length === 2 ? getStore(model, identifier) : getStore(model); } exports.useStore = useStore; /** * Method used to retrieve a store from outside a component. * @param model mobx-state-tree model * @param identifier The identifier used for the store (optional) * @returns The store instance */ function getStore(model, identifier) { return retrieveStore(arguments.length === 2 ? identifier : model) .context; } exports.getStore = getStore;