Why does getFieldState work withe useFieldArray, is it because the field array is not an actuall field. #13607
|
I dont understand why getFieldState is not able to pin down wether a field in a useFieldArray hook is dirty and I have to write more code to get that |
Replies: 1 comment
|
Yes, that is basically the reason: the field array name itself is not the same thing as an individual registered input field.
items.0.name
items.0.price
items.1.nameSo const state = getFieldState('items.${index}.name', formState)
console.log(state.isDirty)For array-level dirty state, use const { control } = useForm({
defaultValues: {
items: [{ name: '' }],
},
})
const { dirtyFields } = useFormState({
control,
name: 'items',
})
const isAnyItemDirty = !!dirtyFields.itemsA couple of important details:
So the short version is: |
Yes, that is basically the reason: the field array name itself is not the same thing as an individual registered input field.
useFieldArray({ name: 'items' })manages the array structure, but the actual registered fields are usually paths like:So
getFieldState('items')is not usually the right way to ask "is any row in this array dirty?". It is better for a concrete field path:For array-level dirty state, use
formState.dirtyFieldsoruseFormStateand inspect the array branch: