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

  1. Go to https://codesandbox.io/s/react-hook-form-controller-jsgm6
  2. Select Strawberry as a value for the first input
  3. Append another input
  4. Remove the input you’ve just added
  5. 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)

Most upvoted comments

yeah. i am preparing the PR

i think we need to make it clear that the default value should be field element of fieldArray <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 😂

To Reproduce

Go to https://codesandbox.io/s/react-hook-form-controller-jsgm6 Select Strawberry as a value for the first input Append another input Remove the input you’ve just added The value of the first input gets reset the default value

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

image

registerField gets called twice on component mount. but basically, this useEffect block may not be necessary because we already including registerField in the deps list of the useEffect block above and calling registerField

oh, cool @deebov thanks for the investigation. would like you like to send a PR if you have a solution?

sure!