Describe the bug
When using nested field array, remove has stopped working properly on version 6.15.2 and 6.15.3.
Calling remove on the parent field array is not behaving as expected. Instead, the fields are somehow being replaced with empty fields while maintaining the same array length. Also, the field id undefined
for the new fields.
I created a minimal CodeSandbox to demonstrate the bug:
To Reproduce
Steps to reproduce the behavior:
- Go to the CodeSandbox provided below.
- Click on add child.
- Click on remove child.
- The child is not removed and react will show a warning saying
Warning: Each child in a list should have a unique "key" prop.
- downgrade to version 6.15.1
- add children and nested children and remove them.
- notice how no errors are shown and that remove is behaving as expected!
Codesandbox link (Required)
https://codesandbox.io/s/hook-form-nested-field-array-t4m3g?file=/src/App.js
Expected behavior
Remove should behave like it did before on earlier versions.
Desktop (please complete the following information):
- OS: macOS
- Chrome 88
- 6.15.3
Additional context
I might be wrong, but I think this is related to #4172
@Elia-Darwish @bluebill1049
It seems the root cause is from line 511 in useFieldArray.ts, not from #4172.
react-hook-form/src/useFieldArray.ts
Lines 506 to 512
in
c67d145
It should be
But fixing this line it’s not enough because it will lead into another issue where “fieldArrayValuesRef.current” after appending new item is something like:
When removing that item, with the name is “children[0].nested” in this case, the method “unset” from utils/unset.ts only removes item reference by using native method “delete” therefore array “children” will be empty but its length is still 1. It will lead into undefined error when trying to add child again because position “0” is now undefined and the new added item will be at position “1”.
react-hook-form/src/utils/unset.ts
Line 53
in
c67d145
@bluebill1049 : Can we use Array.prototype.splice() if the target object to be unset is an array ?
@bluebill1049 @Elia-Darwish
PR is created at #4262
We don’t need to correct unset 😀 It’s my mistake to not correct the nest child in the CSB sample.