UNPKG

react-formal

Version:

Classy HTML form management for React

49 lines (47 loc) 1.27 kB
import React from 'react'; import { EMPTY_ERRORS } from './Errors'; export const BITS = { errors: 1 << 1, // =2 touched: 1 << 2, // =4 actions: 1 << 3, // =8 submits: 1 << 4, // =16 resets: 1 << 5 // =32 }; export const FormContext = /*#__PURE__*/React.createContext({ errors: EMPTY_ERRORS, touched: {}, actions: null, submits: { submitCount: 0, submitAttempts: 0, submitting: false }, resets: 0 }, // @ts-ignore (a, b) => { let bits = 0; if (a.errors !== b.errors) bits |= BITS.errors; if (a.touched !== b.touched) bits |= BITS.touched; if (a.actions !== b.actions) bits |= BITS.actions; if (a.submits !== b.submits) bits |= BITS.submits; if (a.resets !== b.resets) bits |= BITS.resets; return bits; }); // ref: https://github.com/dai-shi/react-hooks-global-state/issues/5 export const useFormContext = observedBits => { const { ReactCurrentDispatcher } = // @ts-ignore React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; const dispatcher = ReactCurrentDispatcher.current; if (!dispatcher) { throw new Error('Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)'); } return dispatcher.useContext(FormContext, observedBits); };