UNPKG

@croct/plug-react

Version:

React components and hooks to plug your React applications into Croct.

63 lines (62 loc) 1.58 kB
"use client"; import { jsx } from "react/jsx-runtime"; import { createContext, useContext, useEffect, useMemo, useRef } from "react"; import { croct } from "./ssr-polyfills.js"; const CroctContext = createContext(null); CroctContext.displayName = "CroctContext"; function useLiveRef(value) { const ref = useRef(value); ref.current = value; return ref; } const CroctProvider = (props) => { const { children, ...configuration } = props; const parent = useContext(CroctContext); const baseConfiguration = useLiveRef(configuration); if (parent !== null) { throw new Error( "You cannot render <CroctProvider> inside another <CroctProvider>. Croct should only be initialized once in the application." ); } const context = useMemo( () => ({ get plug() { if (!croct.initialized) { croct.plug(baseConfiguration.current); } return new Proxy(croct, { get: function getProperty(target, property) { if (property === "plug") { return (options) => { target.plug({ ...baseConfiguration.current, ...options }); }; } return target[property]; } }); } }), [baseConfiguration] ); useEffect( () => { croct.plug(baseConfiguration.current); return () => { croct.unplug().catch(() => { }); }; }, [baseConfiguration] ); return /* @__PURE__ */ jsx(CroctContext.Provider, { value: context, children }); }; export { CroctContext, CroctProvider };