Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit react-hook-form programmatically?

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?

like image 251
Sadegh Eskandari Avatar asked Sep 13 '25 15:09

Sadegh Eskandari


2 Answers

formRef.current.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }))
like image 62
CyberGenius Avatar answered Sep 15 '25 05:09

CyberGenius


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>
  );
}
like image 39
Can Rau Avatar answered Sep 15 '25 05:09

Can Rau