[BUG] useFieldArray fields empty on second visit when using useForm
Describe the bug
useFieldArray.fields is empty when navigating back to an edit form that uses useForm in a SPA. On the first visit the fields populate correctly, but on every subsequent visit they do not.
Potential fix:
- applyValuesToFields(getRegisteredFields(), data, false);
+ reset(data, { keepDirtyValues: true });
Here: https://github.com/refinedev/refine/blob/main/packages/react-hook-form/src/useForm/index.ts#L271
Steps To Reproduce
Minimal reproducible example on codesandbox here: https://codesandbox.io/p/sandbox/t6pxft.
- Go to the edit page ->
useFieldArray.fieldsis populated properly - Go back to the list page
- Go back to the edit page -> no fields returned by
useFieldArray - Repeat steps 2 and 3 notice how it is consistently reproducible.
- Perform a full page refresh -> form works again (one time)
Expected behavior
fields should reflect the array returned by getOne
Packages
- @refinedev/core: 5.0.12
- @refinedev/react-hook-form: 5.0.4
Additional Context
The issue seems to be specifically when the useFieldArray is guarded behind the useForm's formLoading value, indicating a possible race condition.
Workaround
Do not guard components containing useFieldArray by formLoading. Prevent guarding at all or guard with query.data, e.g.:
- {formLoading && <ComponentContainingUseFieldArray />}
+ {query?.data && <ComponentContainingUseFieldArray />}
Additional comments
Update 29-04: the same root issue seems to cause an issue when useFieldArray is used with useForm on a MUI Grid. See https://codesandbox.io/p/sandbox/refine-fieldarray-datagrid-2-76m996. The currently open PR appears to fix both (at least in our environment).
I can reproduce this on my end. The issue is that applyValuesToFields() misses useFieldArray fields because they register after the microtask runs. Using reset() instead handles field arrays natively through RHF. Working on a PR.
I am looking into this
Hi, I’d like to take this up.
I’ll investigate the useFieldArray empty-on-second-visit behavior in @refinedev/react-hook-form, reproduce it with a focused test case, and open a PR with a fix once I’ve isolated the root cause.
Can i try ??
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.