UNPKG

@ryo-98/react-api-bridge

Version:
43 lines (42 loc) 1.49 kB
import { useHookId } from "../utils/useHookId.js"; import { useEffect, useRef } from "react"; import { mountHookInitEffect } from "./mountHookInitEffect.js"; import { removeFromMappedSet } from "../utils/mappedSet.js"; function useInitEffect(onInit, name, apiNList, contextValue, cacheInitCbMap, bridgeOptions, initializedOnInitMap) { const hookId = useHookId(); const callbackInfoRef = useRef(void 0); useEffect(() => { if (!onInit) return; let cacheCbs = cacheInitCbMap.get(apiNList); if (!cacheCbs) { cacheCbs = /* @__PURE__ */ new Map(); cacheInitCbMap.set(apiNList, cacheCbs); } const callbackInfo = { onInit, touchedRefs: /* @__PURE__ */ new Set() }; callbackInfoRef.current = callbackInfo; cacheCbs.set(hookId, callbackInfo); const clearInitEffect = mountHookInitEffect(name, onInit, apiNList, hookId, bridgeOptions, initializedOnInitMap, callbackInfo.touchedRefs); return () => { cacheCbs.delete(hookId); if (cacheCbs.size === 0) { cacheInitCbMap.delete(apiNList); } clearInitEffect?.(); callbackInfo.touchedRefs.forEach((apiRef) => { removeFromMappedSet(initializedOnInitMap, apiRef, hookId); }); callbackInfo.touchedRefs.clear(); callbackInfoRef.current = void 0; }; }, []); useEffect(() => { if (!onInit || !callbackInfoRef.current) return; callbackInfoRef.current.onInit = onInit; }, [onInit]); } export { useInitEffect };