My dev notes about how to set value with React Hook Form. Following the official documentationyou can set a value with React Hook Form using the setValue
method to change it programmatically like this:
const { setValue } = useForm();
...
setValue("firstName", "bill");
But this is wrong!
You have to use the setValue
method to change the value of a field programmatically, but only using the useFormContext
hook instead of the useForm
hook:
const { setValue } = useFormContext();
...
// Somewhere inside the form
setValue("firstName", "bill");
Remember: the first one is used during initialization of the form, the second one is used inside the form.
Top comments (2)
Using the setValue of useFormContext the value of a field change programmatically but the save button of form is disabled anyway.
The save button is only enabled if i change the field manually.
Any tip to solve that? (Im using SimpleForm of react_admin)
Have you checked list of touched fields when using setValue?