How can we know form is modified or not in react-hook-form. Anyone have idea. I want know if any of the value is changed and update the state edited to true.
After i provide the defaultValue to useForm({defaultValues:values}). I want to notified when the values is updated or changed from defaultValue.
Use isDirty
property
function YourComponent() {
const { formState } = useForm();
const isFormEdited = formState.isDirty;
....
Here is the docs reference
You can use dirtyFields from formstate also, check the length of the fields modified.
const [isEdited, setIsEdited] = useState(false);
const fieldsEdited = formState.dirtyFields;
useEffect(() => {
if (Object.keys(fieldsEdited).length > 0) {
setIsEdited(true);
} else {
setIsEdited(false);
}
}, [fieldsEdited]);
Figured out how to accomplished this. It is important to specify the defaultValues property.
See the isDirty section of formState documentation :
Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.
And a short example:
const {
formState: {
isDirty,
},
} = useForm<ProfileFormInterface>({
defaultValues: {name: 'John Doe', email: 'jd@johndoe.com'},
})
isDirty
will now only be true if the name or email changes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.