UNPKG

react-formal

Version:

Classy HTML form management for React

30 lines 1.05 kB
import { useCallback, useMemo } from 'react'; import { BITS, useFormContext } from './Contexts'; import useErrors from './useErrors'; /** * * @param options * @param {string[]} options.trigger A set of paths to trigger validation for */ export default function useFormSubmit({ triggers } = {}) { const { actions, submits } = useFormContext(BITS.actions | BITS.submits); const errors = useErrors(triggers); const handleSubmit = useCallback((...args) => { if (!actions) { if (process.env.NODE_ENV !== 'production') return console.error('A Form submit event ' + 'was triggered from a component outside the context of a Form. ' + 'The Button should be wrapped in a Form component'); } if (triggers && triggers.length) { actions.onValidate(triggers, 'submit', args); } else actions.onSubmit(); }, // eslint-disable-next-line react-hooks/exhaustive-deps [actions, triggers && triggers.join(',')]); return [handleSubmit, useMemo(() => Object.assign({ errors }, submits), [errors, submits])]; }