React Hook Form is a powerful library for managing forms in React, offering excellent performance and a flexible API. However, there are scenarios where you might want to create a form that does not behave exactly like a standard form. Sometimes form data needs to be submitted automatically when changes occur. This is particularly useful for forms that require real-time validation and submission, such as search forms or dynamic filtering interfaces.
Let's say, we have a simple search form for emails.
import { useForm } from 'react-hook-form'; interface FormValues { content: string; email: string; } const SearchForm = () => { const { register, handleSubmit } = useForm(); const onSubmit = (data: FormValues) => { console.log('Form submitted:', data); }; return ( ); };
But then we might want to remove the "Submit" button and submit data without it. To do that, we can create a custom reusable hook that will automatically submit the form when it changes.
import { debounce } from 'lodash'; import { useCallback, useEffect, useState } from 'react'; import { type UseFormWatch, type FieldValues, type UseFormTrigger, type Path } from 'react-hook-form'; interface AutoSubmitProps{ trigger: UseFormTrigger ; watch: UseFormWatch ; excludeFields?: Path []; onSubmit: () => void; onValidationFailed?: () => void; debounceTime?: number; } /** * Automatically submit data when it's changed */ export const useAutoSubmit = ({ trigger, watch, onSubmit, debounceTime = 500, excludeFields, onValidationFailed, }: AutoSubmitProps ) => { const [isSubmiting, setIsSubmiting] = useState(false); const debouncedSumbit = useCallback( debounce((submitFn: () => void) => { submitFn(); }, debounceTime), [], ); useEffect(() => { const subscription = watch((_data, info) => { if (info?.type !== 'change') return; if (info.name && excludeFields?.includes(info.name)) return; setIsSubmiting(true); trigger() .then((valid) => { if (valid) debouncedSumbit(onSubmit); else onValidationFailed?.(); }) .finally(() => setIsSubmiting(false)); }); return () => subscription.unsubscribe(); }, [watch, onSubmit]); return { isSubmiting }; };
The hook automatically triggers form validation when a field changes. If the validation is successful, it debounces the submission to avoid excessive requests.
import { useForm } from 'react-hook-form'; import { useAutoSubmit } from './useAutoSubmit'; interface FormValues { content: string; email: string; } const SearchForm = () => { const { register, handleSubmit, trigger, watch } = useForm(); const onSubmit = (data: FormValues) => { console.log('Form submitted:', data); }; useAutoSubmit({ trigger, watch, onSubmit: handleSubmit(onSubmit), }); return ( ); };
The useAutoSubmit hook simplifies the process of automatically submitting forms in React applications. By using this hook, you can ensure that your forms are always up-to-date with the latest user input, reducing the need for manual submissions and enhancing the overall user experience
Snippet source code
The above is the detailed content of Automatically submitting forms in react-hook-form. For more information, please follow other related articles on the PHP Chinese website!