Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit with React Hook Form when having mode onBlur?

This is not like what this question is asking.

Basically, I have a form that I want to auto-submit whenever fields are changed. I.e. I do not want a submit button.

So, having this:

const {
  formState,
  handleSubmit
} = useForm<TSaveInputSchema>({
  mode: "onBlur",
  reValidateMode: "onChange",
  criteriaMode: "firstError",
  resolver: zodResolver(saveInputSchema),
});

const handleSave = useCallback<HandleSaveCallback>(
  (data) => {
    console.log("DATA SUBMIT", data);
  }
), []);

And HTML like this:

<form onSubmit={handleSubmit(handleSave)}>
  <input {...register("name")} />
</form>

does not call the handleSave function when the input field is blurred.

How can this be done, if possible? Or do I have to manually trigger the submit through other means (e.g. using useEffect)?

like image 942
Yanick Rochon Avatar asked Feb 25 '26 15:02

Yanick Rochon


2 Answers

Too much refactor for the day, the solution was dumb:

Replace

<form onSubmit={handleSubmit(handleSave)}>
  <input {...register("name")} />
</form>

with

<input {...register("name", { onBlur:handleSubmit(handleSave) )} />
like image 172
Yanick Rochon Avatar answered Feb 28 '26 06:02

Yanick Rochon


Found this: https://github.com/orgs/react-hook-form/discussions/2494#discussioncomment-1843760

Fiddled around and looks like this is just working (now?):

<form onBlur={handleSubmit(handleSave)}>
like image 22
escapedcat Avatar answered Feb 28 '26 04:02

escapedcat