UNPKG

dreamstate

Version:

Store management library based on react context and observers

36 lines (33 loc) 1.43 kB
import { createContext } from 'react'; import { CONTEXT_REACT_CONTEXTS_REGISTRY } from '../internals.js'; /** * Retrieves the React context reference associated with the provided `ManagerClass`. * The context is lazily created only after the first access attempt. If no manager is provided in the scope, * a default context value can be applied. * * This function allows for the dynamic creation and retrieval of a context specific to a given manager, * ensuring that the context is properly initialized and available for use. * * @template S - The type of the context state. * @template M - The type of the context manager constructor. * @param {M} ManagerClass - The context manager constructor reference used to identify the context. * @returns {Context<S>} - A React context instance with a pre-defined default value. */ function getReactContext(ManagerClass) { var existing = CONTEXT_REACT_CONTEXTS_REGISTRY.get(ManagerClass); if (existing) { return existing; } else { var reactContext = createContext(ManagerClass.getDefaultContext()); /* * Later providers and consumers in tree will be displayed as * 'Dreamstate.Class.Provider' or 'Dreamstate.Class.Consumer'. */ { reactContext.displayName = "Dreamstate." + ManagerClass.name; } CONTEXT_REACT_CONTEXTS_REGISTRY.set(ManagerClass, reactContext); return reactContext; } } export { getReactContext };