issue: values data is reset after first render, when shouldUnregister is provided…
- User
issue:
valuesdata is reset after first render, whenshouldUnregisteris providedVersion Number
7.71.2
Codesandbox/Expo snack
https://codesandbox.io/p/sandbox/blazing-dust-3225h9?file=%2Fsrc%2FApp.js
Steps to reproduce
- Simply submit a form
- See error
Expected behaviour
It is possible to successfully submit a form, when data is provided via
values, andshouldUnregister: trueoption is setWhat browsers are you seeing the problem on?
Chrome
Code of Conduct
- I agree to follow this project's Code of Conduct
Interface
No new interfaces are introduced.
- Assistant
Investigating how
valuesandshouldUnregisterinteract in the codebase. - Assistant
Identified the bug:
_resetcallssetValuefor mounted fields, then clears_formValueswhenshouldUnregisteris true. Writing a test and applying the fix. - Assistant
Implementing the fix: moving
_formValuesassignment before field population viasetValue. - Assistant
Fixed a bug where
_resetpopulated mounted fields viasetValue, then immediately cleared_formValueswhenshouldUnregister: true.Root cause
In
_reset, when thevaluesprop triggers a reset withkeepFieldsRef: true:setValueran for each mounted field and wrote into_formValues_formValueswas then set to{}becauseshouldUnregisterwas true- On submit,
handleSubmitread from the empty_formValues, so the form submitted{}
Fix
In
createFormControl.ts,_formValuesis now assigned before field values are written viasetValue. The same ordering applies to thekeepDirtyValuespath, which had the same issue.Test
Added a regression test in
useForm.test.tsxthat covers:valuesprop providing form datashouldUnregister: true- Successful form submission with the expected values
Without the fix, the test fails with
submittedDataas{}; with it, submission returns as expected.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.