react-hook-form: Error for field array item isn't cleared when registered control is removed

Describe the bug Error prop for field array item isn’t cleared when the corresponding registered control is removed from the DOM.

To Reproduce Steps to reproduce the behavior:

  1. Click on ‘Remove Item C’.
  2. Observe error messages in the “Error Bar”.

Codesandbox link (Required) https://codesandbox.io/s/rhf-error-fieldarrayitem-when-control-removed-4cu0w?file=/src/index.jsx

Expected behavior Error message “Item A is required” should not be in the Error Bar since the corresponding registered control for Item A is removed from the DOM when Item C is removed. Error message “Item B is required” should stay put.

Additional context Actually, the logic I’ve got in my project to show/hide some form controls based on the existence of some other form controls in the DOM is much more complex than what depicted in the CSB. So I would like to rely on the “automatic” removal of the error for such control that’s no longer in the DOM, rather than using the “manual” clearErrors(...) API. 😬

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 26 (13 by maintainers)

Commits related to this issue

Most upvoted comments

no worries at all @dwiyatci feel free to follow me up with questions here if you stuck again.

No, I don’t have the CSB for it. But aw yeah, turns out after stitching it more carefully with useWatch, Option B seems to do the job for me. 🤩 I left the Option A out 'cause it’d require quite some structural changes in the code. Thanks, again, so much for the valuable hint @bluebill1049 !

However, along with the experimentation, I found another (little detail) annoying thing when using useWatch instead of watch. But that’s another issue. Gonna create a new one and gonna close this one now 😃

Thanks a lot. Have a good lunch and rest of the day for now then… 🥘 ⛅

Umm, I don’t think that’s the issue, @bluebill1049. What I mean is not about what the watch returns. It’s just that whenever I use watch('fieldArray', ...), the error is not cleared as expected. Please try to:

  1. Comment/uncomment line number 28.
  2. Click “Remove Item C”.
  3. Compare the results.

oh! sorry miss that issue, i will investigate tonight.

@bluebill1049 Aaa ok. Thanks so much for the effort! 🙇🏻‍♂️

@dwiyatci looks like trigger need to clean all errors to get this working. i am patching this with a PR.

https://codesandbox.io/s/rhf-error-fieldarrayitem-when-control-removed-forked-drt9c?file=/src/src/useForm.ts

Umm, sorry. 🙄 I don’t think it needs to be outside of the App though.

There, I basically want to express sth like: “Only render item A if item C exists”

I can surely make the CSB clearer again tomorrow if it needs be (since it’s already past midnight here, I only changed shouldShow to shouldRenderItem for now). Thanks Bill!!