React hook Form know when value is modified
Asked Answered
T

4

17

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.

This answered 19/7, 2020 at 13:50 Comment(0)
P
23

Use isDirty property

function YourComponent() {
 const { formState } = useForm();
 const isFormEdited = formState.isDirty;
 ....

Here is the docs reference

Piny answered 19/7, 2020 at 14:31 Comment(4)
Problem is clicking into a field, not changing anything, and then clicking out of it again already sets this to true.Markos
works fine for me in react native.Beetroot
@Adam B: Read the answer of JimmiArmijo
also refer this answer for the complete stuff.. https://mcmap.net/q/743446/-react-hook-form-check-for-unsaved-changesTetchy
A
12

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: '[email protected]'},
  })

isDirty will now only be true if the name or email changes.

Appellative answered 22/9, 2021 at 9:14 Comment(0)
U
6

I faced the same problem, even using isDirty didn't actually help, so I solved it using dirtyFields like this:

if (Object.keys(dirtyFields).length === 0) {
    // Do something when there are no dirty fields
}
Unrequited answered 24/1, 2024 at 11:49 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewLewin
N
0

For your usecase, you can use isDirty property provided by react-hook-form. But to use it, you must have some defaultValues for the fields.

You can see the following example which is mentioned in the documentation itself,

const {
  formState: { isDirty },
  setValue,
} = useForm({ defaultValues: { test: "" } });


// isDirty: true
setValue('test', 'change')
 
// isDirty: false because there getValues() === defaultValues
setValue('test', '')

Also, check the if you are providing the defaultValues in correct manner. There might be some issues with values you are using in your code.

useForm({defaultValues:values})
Nock answered 12/6, 2024 at 12:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.