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);
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]);
If you log your implementation of handleSubmit inside onChange, you will notice that it returns a function

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
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