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 pass the form data when form validation is successful.

Rules

  • You can easily submit form async 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 input will be returned undefined as result, if you want to prevent users from update the input, you can use readOnly or disable the entire <fieldset />. Here is an example.

Props

NameTypeDescription
SubmitHandler(data: Object, e?: Event) => voidA successful callback.
SubmitErrorHandler(errors: Object, e?: Event) => void) => voidAn error callback.
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, 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>
  );
}
import React from "react";
import { useForm } from "react-hook-form";

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

function App() {
  const { register, handleSubmit, 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>
  );
}
Edit