I am using react-hook-form. I have a field with onChange set. When I use setValue on this field, I expect onChange to be triggered, but it is not. Why is onChange not working after calling setValue?
import { Box, TextField, FormLabel, Button } from "@mui/material";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import "./App.css";
interface TestForm {
name: string;
}
const validationSchema = z.object({
name: z.string().nonempty().min(4),
});
function SetSample() {
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm<TestForm>({
mode: "onBlur",
shouldUnregister: false,
resolver: zodResolver(validationSchema),
});
const handleOnChange = async (e: React.FocusEvent<HTMLInputElement>) => {
console.log("handleOnChange:" + e.target.value);
};
const handleButtonClick = () => {
console.log("onClick");
setValue("name", "button click", { shouldDirty: true });
};
const onSubmit = (data: TestForm) => {
console.log("Submitted Data", data);
};
return (
<div className="form-container">
<h1>React-Hook-Form</h1>
<Box>
<Button onClick={handleButtonClick}>Sample</Button>
</Box>
<form onSubmit={handleSubmit(onSubmit)}>
<Box mb={2}>
<FormLabel>Name</FormLabel>
<TextField
type="text"
{...register("name")}
onChange={handleOnChange}
error={!!errors.name}
helperText={errors.name?.message}
/>
</Box>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default SetSample;
Usage version.
- “react”: “^18.2.0”,
- “react-hook-form”: “^7.45.1”