UNPKG

@exabytellc/utils

Version:

EB react utils to make everything a little easier!

64 lines (59 loc) 1.99 kB
import React from "react"; import { createContext, useContext } from "react"; /** * Creates a Bloc context with a provider and a hook to access the context value. * * @param {Function} initializer - Function to initialize the context value. * @returns {{ Use: Function, Context: React.Context, Provider: Function }} - Object containing the context, hook, and provider. */ import { jsx as _jsx } from "react/jsx-runtime"; export default function createBlocContext() { let initializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : () => {}; const Context = /*#__PURE__*/createContext(null); /** * Hook to access the Bloc context value. * * @returns {*} - The context value. * @throws {Error} - If used outside of a provider. */ const useBloc = () => { const ctx = useContext(Context); if (ctx === null) { throw new Error("Context must be used within a provider!"); } return ctx; }; /** * Provider component for the Bloc context. * * @param {Object} props - Props for the provider component. * @param {React.ReactNode} props.children - The children components to be wrapped by the provider. * @returns {JSX.Element} - The provider component. */ // eslint-disable-next-line react/prop-types const Provider = _ref => { let { children, ...props } = _ref; return /*#__PURE__*/_jsx(Context.Provider, { value: initializer(props), children: children }); }; /** * Higher-order function to provide additional props to the context. * * @param {Object} props - Additional props for the provider. * @returns {Function} - The modified hook with additional props. */ const withProps = props => { useBloc.props = props; return useBloc; }; // Attach the Context and Provider to the useBloc hook useBloc.Context = Context; useBloc.Provider = Provider; useBloc.withProps = withProps; return useBloc; }