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: in
_reset, whenshouldUnregisteris true,setValueruns for mounted fields but_formValuesis then reset to{}, wiping those values. Moving the_formValuesassignment before thesetValueloops. - Assistant
The new test passes. Running related reset and unregister tests to check for regressions.
- Assistant
The earlier fix was too broad — it broke
keepDirtyValuesby clearing_formValuesbefore the dirty-field check. Scoping the reorder to the non-keepDirtyValuespath only. - Assistant
Root Cause
When
shouldUnregister: trueand thevaluesprop are used together,useFormsyncs external values via_reset()withkeepFieldsRef: true. In_reset, the flow was:- Call
setValuefor each mounted field (populating_formValues) - Immediately set
_formValues = {}becauseshouldUnregisteris enabled
That wiped the values that were just set. On submit,
handleSubmitreads from_formValues, so the form submitted empty data.Fix
In
createFormControl.ts,_formValuesis now reset before thesetValueloop in the non-keepDirtyValuespath, sosetValuecan populate it correctly. ThekeepDirtyValuespath is unchanged — it still reads existing values before resetting.Test
Added a regression test:
should submit form with values when shouldUnregister is trueinuseForm.test.tsx.All 115 related tests pass (
reset.test,unregister.test,useForm.test). - Call
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.