UNPKG

informed

Version:

A lightweight framework and utility for building powerful forms in React applications

37 lines (34 loc) 1.44 kB
import { useMemo, useRef, useEffect } from 'react'; import { useFormController } from './useFormController.js'; import { createDeepProxy, isDeepChanged } from '../proxy.js'; import { useForceUpdate } from './useForceUpdate.js'; import { structuredClone as structuredCloneShim } from '../structuredClone.js'; function useFormStateSelector(selector) { var formController = useFormController(); var affected = new WeakMap(); var proxyCache = useMemo(function () { return new WeakMap(); }, []); var prevState = useRef(structuredCloneShim(formController.state)); var lastAffected = useRef(affected); var forceUpdate = useForceUpdate(); var selectorStateRef = useRef(selector(createDeepProxy(prevState.current, affected, proxyCache))); var selectorRef = useRef(); selectorRef.current = selector; lastAffected.current = affected; useEffect(function () { var callback = function callback() { if (isDeepChanged(prevState.current, formController.state, lastAffected.current)) { prevState.current = structuredCloneShim(formController.state); selectorStateRef.current = selectorRef.current(createDeepProxy(prevState.current, affected, proxyCache)); forceUpdate(); } }; formController.on('field', callback); return function () { formController.removeListener('field', callback); }; }, []); return selectorStateRef.current; } export { useFormStateSelector };