ISSUE DESCRIPTION issue: values data is reset after first render, when shouldUnregister…
- User
ISSUE DESCRIPTION
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.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /react-hook-form, current file: none) bash-$
Assistant
I'll start by exploring the repository structure to understand the codebase.
Assistant
I need to make only one tool call at a time. Let me explore the repository structure.
Assistant
The main logic file is
createFormControl.ts. Let me look at it, particularly focusing on thevaluesandshouldUnregisterhandling.Assistant
Let me look at the reset function more closely, which is likely where the issue lies.
Assistant
Now let me look at the
resetfunction (the public one) and how it's invoked.Assistant
Now let me look at the
useForm.tsto understand howvaluesanddefaultValuesare passed and how reset is called on mount.Assistant
Let me look at the
setValuefunction and the register logic.Assistant
Let me understand the flow better. Let me look at the
_resetfunction again with thekeepFieldsReflogic.The issue: When
shouldUnregister: trueandvaluesis provided:useEffectcallscontrol._reset(props.values, { keepFieldsRef: true, ...resetOptions })- In
_reset:_defaultValues = updatedValues(props.values)keepFieldsRefis true, so for each mounted field,setValueis called with the value fromvalues_formValues = shouldUnregister ? (keepDefaultValues ? cloneObject(_defaultValues) : {}) : cloneObject(values)- Since
shouldUnregisteris true andkeepDefaultValuesis false:_formValues = {}
So after the reset,
_formValuesis{}, even though we just set values for mounted fields viasetValue.Wait, but
setValuecallssetFieldValuewhich callsset(_formValues, name, ...). So setting_formValues = {}AFTER thesetValueloop would wipe out the values that were just set!Let me re-read the code:
if (keepStateOptions.keepFieldsRef) { for (const fieldName of _names.mount) { setValue( fieldName as FieldPath<TFieldValues>, get(values, fieldName), ); } } else { _fields = {}; }Then AFTER this if/else block:
_formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);So yes, after the
keepFieldsRefloop callssetValue(which populates_formValues),_formValuesis then set to{}whenshouldUnregisteris true andkeepDefaultValuesis false. This wipes out the values!So the fix should be: when
keepFieldsRefis true (which is set whenvaluesis provided in the useEffect), we should NOT reset_formValuesto{}.Let me look at the git blame / history to understand when this was changed.
Actually, let me think about what the correct behavior should be:
- When
shouldUnregisteris true,_formValuesshould only contain registered (mounted) fields. - When we reset with
values, thekeepFieldsRefloop callssetValuefor each mounted field, which populates_formValueswith the values for those mounted fields. - So after the
keepFieldsRefloop,_formValuesalready has the correct values for the mounted fields. - Setting
_formValues = {}after that would wipe them out, which is the bug.
So the fix: when
keepFieldsRefis true, we should keep the_formValuesthat were just populated by thesetValueloop, OR set_formValuesto the clonedvalues.Wait, but actually, the issue is that when
shouldUnregisteris true, the intent of_formValues = {}is to start fresh (only registered fields should be in_formValues). But thekeepFieldsRefloop already handles populating_formValuesviasetValue.Let me check: does
setValueactually populate_formValues? Let me look at thesetValuefunction.Assistant
Let me look at
_setValue.Assistant
Let me first reproduce the issue. Let me look at the test structure.
Assistant
Let me look at existing tests that use
valuesto understand the test format.Assistant
Now let me create a reproduction test to confirm the issue.
Assistant
The cast syntax is causing a parse issue. Let me fix the test.
Assistant
The babel config doesn't support TypeScript
ascasts in this context. Let me check the babel config.Assistant
The transform uses
@swc/jestbut the error shows babel. Let me just avoid type casts in my test.Assistant
The transform isn't being applied. Let me run an existing test to verify the setup works.
Assistant
I need to use the
--configflag. Let me run my repro test with the proper config.Assistant
The simple test passes. Let me look at the actual scenario more carefully. Let me check the
handleSubmitflow and how form values are extracted on submit.Assistant
Let me look at the
registerfunction to understand how fields get their values.Assistant
Let me look at
updateValidAndValue.Assistant
I see - the issue is about timing. In a real component, fields register during render (before the
valuesuseEffect runs). Let me write a component-based reproduction test.Assistant
I've reproduced the issue. The submitted data is
{}instead of{ test: 'data' }. Now let me understand the root cause. Let me look at the_resetfunction and its_formValuesassignment.Assistant
Now I understand the change. Before commit
802b0472,_formValueswas simplycloneObject(values). The commit changed it to wipe_formValuesto{}whenshouldUnregisteris true andkeepDefaultValuesis false. Let me check the test that was added with this commit.Assistant
Let me look at that test in full context to understand what scenario it covers.
Assistant
Let me look at the
isEmptyObjectutility and the_resetfunction structure once more.Assistant
OK so
isEmptyObject(undefined)=isObject(undefined) && ...=false && ...= false. SoisEmpty = false.So for
setValue(fieldName, undefined):isEmpty = false.!field || field._f || isNullOrUndefined(cloneValue) || isEmpty.isNullOrUndefined(undefined)= true. So this condition is true.setFieldValue(fieldName, undefined, {}, false).
setFieldValue:field = get(_fields, name).fieldReference = field._f.!fieldReference.disabled && set(_formValues, name, getFieldValueAs(undefined, fieldReference)).getFieldValueAs(undefined, fieldReference)- let me check.
Let me look at
getFieldValueAs.Assistant
Let me view the exact lines of the
_formValuesassignment in_reset.Assistant
Let me view the full
_resetstructure around thekeepFieldsReflogic to understand the nesting.Assistant
Now I understand the issue clearly. The
keepFieldsRefloop populates_formValuesviasetValue, but then the_formValuesassignment wipes it to{}whenshouldUnregisteris true andkeepDefaultValuesis false. This was introduced by commit802b0472.Let me make the fix. When
keepFieldsRefis true (thevaluesprop case), the loop has already populated_formValueswith the mounted field values, so we should keep them instead of wiping to{}.Assistant
Now let me apply the fix:
Assistant
The fix is applied. Now let me run my reproduction test to confirm the fix works.
Assistant
The fix works - the submitted data is now
{ test: 'data' }instead of{}. Let me think about edge cases and test a few more scenarios. Let me extend my reproduction test to cover edge cases.Assistant
All edge cases pass. Now let me run the existing test suites to make sure I didn't break anything. Let me start with the most relevant ones.
Assistant
All pass (the trace shown was just a
waitForretry log, tests all passed). Let me run the broader test suite includinguseFieldArray,useController,useWatch, andunregistertests sinceshouldUnregisteris related.Assistant
All pass (the trace is just a React
actwarning, not a failure). Let me run the fulluseFormtest directory plus field array tests to be thorough.Assistant
All 489 tests pass. Let me run the entire test suite to be extra safe.
Assistant
All 1124 tests pass across 119 test suites (both Web and Server projects). Now let me clean up my reproduction test file before submitting.
Assistant
I see
package.jsonis also modified, which I didn't intend. Let me check the diff.Assistant
This
package.jsonchange is unrelated to my fix (likely a pre-existing environment artifact). Let me revert it to keep my submission clean.Assistant
The diff is now clean - only the relevant change. Let me do a final verification by recreating and running the reproduction test, then cleaning up.
Assistant
The fix works and the reproduction test is cleaned up. Let me verify the final state of the repository.
Assistant
The change is clean and minimal. Let me review the final fix once more in context:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →