UNPKG

dynamic-modal

Version:

The dynamic-modal is a solution of creation different modals into project using a json configuration file

63 lines (62 loc) 2.39 kB
'use client'; import { useEffect, useEffectEvent, useRef } from 'react'; const useConditionalField = ({ watch, elementName, renderIf, enableIf, liveDataConfig, render, enable, checkRender, checkEnable, checkLiveData, setRender, setEnable, setLiveData, setLiveSearching, unregister, setValue, liveDataResetValue, }) => { const liveRequestId = useRef(0); const handleWatchChange = useEffectEvent(async (formData, meta) => { if (enableIf) { const enableStatus = await checkEnable(formData, meta); if (enableStatus !== undefined && enableStatus !== null && enable !== enableStatus) { setEnable(enableStatus); } } if (renderIf) { const renderStatus = await checkRender(formData, meta); if (renderStatus !== undefined && renderStatus !== null && render !== renderStatus) { if (render && !renderStatus) unregister?.(elementName); setRender(renderStatus); } } const shouldResolveLiveData = Boolean(liveDataConfig?.condition?.includes(meta.name)); if (shouldResolveLiveData && setLiveData) { const requestId = ++liveRequestId.current; setLiveSearching?.(true); try { const options = await checkLiveData(formData, meta); if (requestId !== liveRequestId.current || options === undefined || options === null) { return; } setLiveData(options); if (setValue) { setValue(elementName, liveDataResetValue ?? []); } } finally { if (requestId === liveRequestId.current) { setLiveSearching?.(false); } } } }); useEffect(() => { const { unsubscribe } = watch((formData, meta) => { if (!meta.name) return; void handleWatchChange(formData, { name: meta.name, type: meta.type, }); }); return () => { liveRequestId.current += 1; unsubscribe(); }; }, [watch]); }; export default useConditionalField;