Calling setValue on array fields causes inconsistencies in form values
See original GitHub issueDescribe the bug Whenever setValue is called using an array field there seem to be inconsistencies between the data returned via watch and getValues. I have tried patch 3.22.1-beta8 and that does seem to resolve some inconsistencies but introduces other other issues such as values not being prefilled into inputs.
To Reproduce I’ve setup a sandbox and hopefully that will clarify some of the issues I am encountering. Please correct me if I am misusing the code.
Steps to reproduce the behavior:
Inconsistencies with (3.22.1)
- Go to https://codesandbox.io/s/react-hook-form-array-field-inconsistencies-if4m7
- You will see that the fields are pre-populated as they should be.
- Go ahead and click on
Remove Friend
on any of the two listed. You will notice that the watch values are correct, however the formValues are not correct. - Go ahead and click
Add Friend
and you will notice the default value for that index is restore rather than an empty new entry being added.
Inconsistencies with (3.22.2-beta8)
- Go to https://codesandbox.io/s/react-hook-form-array-field-inconsistencies-if4m7
- Go to the dependencies on the left panel and update the react-hook-form dependency to version 3.22.2-beta8.
- You’ll notice that the input fields are no longer prefilled when they should be like in version 3.22.1. The data is correct in both
watch
andgetValues
however there seems to be disconnect between the inputs and the data. I can register the input’s differently by not passing register({ name }) which will render correctly, however that will disallow me to call setValue and pass in an array explicitly. - Go ahead and click
Remove Friend
on any of the two entries. Doing so will remove the friend correctly from the data, but again the inputs do not display in input values.
Expected behavior
In the particular sandbox that I setup I figure calling setValue(friends
, arrayOfFriends) should update the formValues correctly and also update the field inputs. Also clearing the fields and then adding new one should no longer use defaultValues to prefill the inputs.
Desktop (please complete the following information):
- OS: MacOs Mojave
- Browsers: Firefox 68.0.2 Chrome 76.0.3809.100
Issue Analytics
- State:
- Created 4 years ago
- Comments:21 (15 by maintainers)
This setup seems to work. Basically, add a
useEffect
to iterate over the list any time it changes andsetValue
for each index and key combo:https://codesandbox.io/s/react-hook-form-array-field-inconsistencies-gl3nr
The exception is that
setValue
will cause an infinite render if it’s included in the dep list for theuseEffect
.Thank you! And great work on this library, I’ve been enjoying it!