Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit react form fields on onChange rather than on submit using React-Hook-Form library

I have started using new React-Hook-form library and wanted to submit my input fields on Change rather than on Submit. Also, I am planning to use debounce from Lodash to avoid re-rendering

This is what I have tried so far:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

export default function App() {
  const { register, handleSubmit, setValue } = useForm();
 

  useEffect(() => {
    register({ name: "firstName" }, { required: true });
  }, [register]);

  return (
    <form>
      <input
        name="firstName"
        onChange={(e) => {
          setValue("firstName", e.target.value);
          handleSubmit((data) => console.log("data", data));
        }}
      />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
like image 331
Eva Avatar asked Dec 19 '25 15:12

Eva


2 Answers

I found the simplest way to be:

const { handleSubmit, watch } = useForm();
const onSubmit = (data) => console.log(data)

useEffect(() => {
    // TypeScript users 
    // const subscription = watch(() => handleSubmit(onSubmit)())
    const subscription = watch(handleSubmit(onSubmit));
    return () => subscription.unsubscribe();
}, [handleSubmit, watch]);
like image 134
Alex Chan Avatar answered Dec 22 '25 05:12

Alex Chan


If you log your implementation of handleSubmit inside onChange, you will notice that it returns a function

enter image description here

Try to invoke the returned function and it should submit.

onChange={(e) => {
    setValue("firstName", e.target.value);
    handleSubmit((data) => console.log("data", data))();
}}

I've also recently written my version of "user is done with typing, then submit" implementation for input fields - check it out: https://stackoverflow.com/a/63419790/8680805

like image 25
95faf8e76605e973 Avatar answered Dec 22 '25 03:12

95faf8e76605e973



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!