handleSubmit:
((data: Object, e?: Event) => void, (errors: Object, e?: Event) => void) => Function
This function will receive the form data if form validation is successful.
Props
Name | Type | Description |
---|---|---|
SubmitHandler | (data: Object, e?: Event) => void | A successful callback. |
SubmitErrorHandler | (errors: Object, e?: Event) => void | An error callback. |
Rules
You can easily submit form asynchronously with handleSubmit.
// It can be invoked remotely as well handleSubmit(onSubmit)(); // You can pass an async function for asynchronous validation. handleSubmit(async (data) => await fetchAPI(data))
disabled
inputs will appear asundefined
values in form values. If you want to prevent users from updating an input and wish to retain the form value, you can usereadOnly
or disable the entire <fieldset />. Here is an example.handleSubmit
function will not swallow errors that occurred inside your onSubmit callback, so we recommend you to try and catch inside async request and handle those errors gracefully for your customers.const onSubmit = () => { // async request which may result error throw new Error("Something is wrong"); }; <> <form onSubmit={(e) => { handleSubmit(onSubmit)(e) // you will have to catch those error and handle them .catch(() => {}); }} /> // The following is a better approach <form onSubmit={handleSubmit(() => { try { request(); } catch (e) { // handle your error state here } })} /> </>;
Examples
import { useForm } from "react-hook-form"; export default function App() { const { register, handleSubmit } = useForm(); const onSubmit = (data, e) => console.log(data, e); const onError = (errors, e) => console.log(errors, e); return ( <form onSubmit={handleSubmit(onSubmit, onError)}> <input {...register("firstName")} /> <input {...register("lastName")} /> <button type="submit">Submit</button> </form> ); }
import React from "react"; import { useForm, SubmitHandler } from "react-hook-form"; type FormValues = { firstName: string; lastName: string; email: string; }; export default function App() { const { register, handleSubmit } = useForm<FormValues>(); const onSubmit: SubmitHandler<FormValues> = data => console.log(data); return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register("firstName")} /> <input {...register("lastName")} /> <input type="email" {...register("email")} /> <input type="submit" /> </form> ); }
Video
The following video tutorial explains the handleSubmit
API in detail.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.