UNPKG

informed

Version:

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

46 lines (38 loc) 1.51 kB
import { useEffect } from 'react'; import { useFormController } from './useFormController.js'; import { useForceUpdate } from './useForceUpdate.js'; import { isChild } from '../utils.js'; import { Debug } from '../debug.js'; import { useScope } from './useScope.js'; var debug = Debug('informed:useFieldState' + '\t'); /* ----------------------- useFieldState ----------------------- */ var useFieldState = function useFieldState(n) { var scoped = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; // Create name var name = scoped ? useScope(n) : n; // Grab the form controller var formController = useFormController(); // Magic trick var forceUpdate = useForceUpdate(); // Register for events on our field useEffect(function () { var listener = function listener(target) { // either // 1. All fields are supposed to update // 2. This is a specific registration "foo" === "foo" // 3. This field is a child of registration "friends[0].name" is a child of name="friends[0]" if (target === '_ALL_' || target === name || target && isChild(name, target)) { debug('Updating', name); forceUpdate(); } }; formController.emitter.on('field', listener); // When name changes we always force an update! forceUpdate(); return function () { formController.emitter.removeListener('field', listener); }; }, [name]); return formController.getFieldState(name); }; export { useFieldState };