react-hook-form: V7: formState.isDirty is not set to true onChange if value is watched
Describe the bug In v7 in a form with only one input the formState.isDirty will not be true when the input is changed if you are watching the form value. It will become true once the input is blurred, however this is not good if the save button is disabled when !form.isDirty as it prevents the user from submitting the form unless they have blurred the input.
If you remove the watch on the form value it works as expected
To Reproduce Create a form with a single input and set the submit button to be disabled if !formState.isDirty
- Watch a field with something similar to what is below or in the codeSandbox
function Form(){
const { register, formState, watch } = useForm()
const { isDirty } = formState
const name = watch('name')
return <form>
<input type='text' {...register('name')} />
<button type='submit' disabled={!isDirty}>Save</button>
</form>
}
- Change the field value
- The submit button will be disabled when it should be enabled
Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-useform-template-forked-rpm8c?file=/src/index.js
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 15 (8 by maintainers)
Commits related to this issue
- fix #4597 watch intercept dirty return value — committed to react-hook-form/react-hook-form by bluebill1049 3 years ago
Brilliant thanks, that works! thanks for the pointer in the docs too.
You want to set the
shouldDirtyflag totruein the third options argument ofsetValue.You can learn more at RHF
setValuemethod docsI’m glad I could help!
Ahha - right, it works now. Thank you.
thanks @Moshyfawn 🙏
By spreading all the
registerprops to your input via{...register("field")}and passing youronChangehandler after, you’re re-assigning the input’sonChangewhich is used by RHF.Please, assign your
onChangehandler as a second options argument toregisterinstead.