How to submit react-hook-form programmatically?
Asked Answered
A

4

15

I'm trying to add a react-hook-form to my react.js project. The form is defined as:

<form onSubmit={handleSubmit(onSubmit)} ref={submitRef}>
          //some input elements
          <div className='d-flex justify-content-center' >
            <button
              type="submit"
              className=" btn btn-warning" >
              submit            
            </button>
          </div>
</form>

The onSubmit method is defined as:

const onSubmit = data => {
    console.log(data)
  };

I'm trying to define a timer (say 10 mins) and I want to trigger the onSubmit event of the form once the timer is expired. For this I used the react-timer-hook as follows:

const time = new Date();
  time.setSeconds(time.getSeconds() + 2);

  let submitRef = useRef()

  const {
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    resume,
    restart,
  } = useTimer({ time, onExpire: () => want to trigger the form submit event });

How should I define the onExpire property?

Altimeter answered 21/9, 2022 at 9:18 Comment(0)
K
17
formRef.current.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }))
Kindle answered 24/11, 2022 at 12:7 Comment(1)
This solution works. handleSubmit(async (data) => await fetchAPI(data)) does not work. Thanks.Hunger
C
8

To do the exact same thing as the submit button do, you should use the requestSubmit method on the form ref.

formRef.current.requestSubmit();

If you want to support older browsers you can use this polyfill:

if (!HTMLFormElement.prototype.requestSubmit) {
  HTMLFormElement.prototype.requestSubmit = function (): void {
    const tempBtn: HTMLButtonElement = document.createElement('button');
    tempBtn.type = 'submit';
    tempBtn.style.display = 'none';
    this.appendChild(tempBtn);
    tempBtn.click();
    this.removeChild(tempBtn);
  };
}
Carmody answered 10/1 at 19:4 Comment(3)
Working answer for me in 2024!Geneviegenevieve
This is not supported in older browsers. I production it caused an issue for Safari 15.x: caniuse.com/?search=requestSubmit Use: https://mcmap.net/q/796487/-how-to-submit-react-hook-form-programmaticallyExpiate
@MartijnCoevert I have modified the answer and included basic polyfill for older browsers without the submitter argument.Carmody
P
7

You can manually invoke handleSubmit

from the docs

// It can be invoked remotely as well
handleSubmit(onSubmit)();

// You can pass an async function for asynchronous validation.
handleSubmit(async (data) => await fetchAPI(data))

something like this (untested)

import { useEffect } from 'react';
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  useEffect(() => {
    handleSubmit(onSubmit)();
  }, [])

  return (
    /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* register your input into the hook by invoking the "register" function */}
      <input defaultValue="test" {...register("example")} />
      
      {/* include validation with required or other standard HTML validation rules */}
      <input {...register("exampleRequired", { required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  );
}
Prasad answered 24/4, 2023 at 12:21 Comment(2)
This will not invoke validation check.Incompletion
Sorry not sure about that, don't have capacity to check right now, hope you found a solution/workaround.Prasad
S
3

You have to first trigger the validations before submitting. Use the trigger function returned from useForm hook. Then invoke the handleSubmit function.

const submitForm = async () => {
  // Trigger validations before submitting
  const isValid = await trigger();
    
  if (isValid) {
    handleSubmit(onSubmit)();
  }
};
Saratov answered 27/12, 2023 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.