Skip to content

handleSubmit

Ready to send to the server

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

NameTypeDescription
SubmitHandler(data: Object, e?: Event) => voidA successful callback.
SubmitErrorHandler(errors: Object, e?: Event) => voidAn 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 as undefined values in form values. If you want to prevent users from updating an input and wish to retain the form value, you can use readOnly or disable the entire <fieldset />. Here is an example.

  • During the callback, if the function itself throws an error inside of handleSubmit, it will not swallow the error itself but bubble it up instead and isSubmitSuccessful will be remained as false.

    const onSubmit = () => {
      throw new Error('Something is wrong')
    }
    
    (event) => handleSubmit(onSubmit)(event).catch((error) => {
      // you will need to catch that error
    })

Examples

import React from "react";
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 } from "react-hook-form";

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

export default function App() {
  const { register, handleSubmit, formState: { errors }, formState } = useForm();
  const onSubmit = async data => {
    await sleep(2000);
    if (data.username === "bill") {
      alert(JSON.stringify(data));
    } else {
      alert("There is an error");
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="username">User Name</label>
      <input placeholder="Bill" {...register("username")} />

      <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.

Edit