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?
formRef.current.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }))
                        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>
  );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With