I try to reset a nested array in react hook form without success I created the following sandbox sandbox
1 Answer
Your problem can be fixed by following the nested useFieldArray example here. That example is created by the library's author. I have no idea why it happens though, it may be a library bug or a quirk because the author never expects you to write code that way..
Basically you need to refactor your code by putting the nested fields in a child component instead of placing everything in one big component. So change this:
const { fields, remove } = useFieldArray({
control,
name: "names"
});
const { fields: nested } = useFieldArray({
control,
name: "names[0].nested"
});
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
<input
name={`names[${index}].firstName`}
defaultValue={`${item.firstName}`}
ref={register()}
/>
<ul>
{nested.map((nestedItem, nestedIndex) => {
return (
<li key={item.id}>
<input
name={`names[${index}].nested[${nestedIndex}].lastName`}
defaultValue={`${nestedItem.lastName}`}
ref={register()}
/>
</li>
);
})}
</ul>
</li>
);
})}
</ul>
To something like this:
Parent
const { fields, remove } = useFieldArray({
control,
name: "names"
});
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
<input
name={`names[${index}].firstName`}
defaultValue={`${item.firstName}`}
ref={register()}
/>
<NestedArray
index={index}
control={control}
register={register}
/>
</li>
);
})}
</ul>
NestedArray
const { fields, remove } = useFieldArray({
control,
name: "names[0].nested"
});
return (
<ul>
{fields.map((nestedItem, nestedIndex) => {
return (
<li key={nestedItem.id}>
<input
name={`names[${index}].nested[${nestedIndex}].lastName`}
defaultValue={`${nestedItem.lastName}`}
ref={register()}
/>
</li>
);
})}
</ul>
);