Bibek
Bibek

Reputation: 331

React hook Form know when value is modified

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.

Upvotes: 20

Views: 58430

Answers (4)

random_coder
random_coder

Reputation: 11

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})

Upvotes: 0

Ghassen Eljday
Ghassen Eljday

Reputation: 118

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
}

Upvotes: 7

Jimmi Jønsson
Jimmi Jønsson

Reputation: 179

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.

Upvotes: 13

Rostyslav
Rostyslav

Reputation: 2866

Use isDirty property

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

Here is the docs reference

Upvotes: 24

Related Questions