react-hook-form: [Controller] isNotFieldArray is not updated properly
Describe the bug
I’ve been getting weird issues because of this bug. I opened an issue but it didn’t get resolved so I decided to get my hands dirty 😅
Controller uses useMemo to calculate isNotFieldArray. But since the useMemo receives a ref as a dependency that does not guarantee that the functions inside useMemo will be triggered whenever the ref changes. https://github.com/facebook/react/issues/15164#issuecomment-474833861 I would be happy to provide a more detailed code but I cannot get into node_modules in CodeSandbox. But putting console.log(isNotFieldArray, isNameInFieldArray(fieldArrayNamesRef.current, name), name) after isNotFieldArray is defined would clearly show the problem ( if you are using Controller inside fieldArray ). What I came up with is to replace fieldArrayNamesRef with fieldArrayNamesRef.current.size in the deps list here https://github.com/react-hook-form/react-hook-form/blob/master/src/controller.tsx#L56
To Reproduce
- Go to https://codesandbox.io/s/react-hook-form-controller-jsgm6
- Select
Strawberryas a value for the first input - Append another input
- Remove the input you’ve just added
- The value of the first input get resetted
Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-controller-jsgm6
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 2
- Comments: 29 (29 by maintainers)
yeah. i am preparing the PR
i think we need to make it clear that the default value should be
fieldelement offieldArray<p> make sure to set <code>defaultValue</code> to <code>field</code> of <code>fields</code> when you want to set default value, remove or reset with inputs. </p>or<p> make sure to set <code>defaultValue</code> to <code>fields[index]</code> when you want to set default value, remove or reset with inputs. </p>thanks )
Yes this is what I am talking about 😂
yeah
@bluebill1049 would you give a little explanation about this part of the code https://github.com/react-hook-form/react-hook-form/blob/4c865d35465b2d8f4e855c5285c4bc25ae2fe45c/src/controller.tsx#L118
registerFieldgets called twice on component mount. but basically, this useEffect block may not be necessary because we already includingregisterFieldin the deps list of the useEffect block above and callingregisterFieldsure!