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.
Assistant
Let me analyze the issue. The problem is about
valuesdata being reset after the first render whenshouldUnregisteris provided. This appears to be a React Hook Form issue.Let me first explore the repository structure to understand the codebase.
Assistant
Let me explore the source code structure to understand the codebase.
Assistant
Let me look at the key files related to
valuesandshouldUnregister. TheuseFormhook is the main entry point andcreateFormControl.tslikely contains the core logic.Assistant
Let me look at the
useForm.tsfile andcreateFormControl.tsto understand howvaluesandshouldUnregisterwork.Assistant
I can see that in
useForm.ts, there's auseEffectthat handlesprops.shouldUnregister:typescriptReact.useEffect(() => { props.shouldUnregister && control._subjects.state.next({ values: control._getWatch(), }); }, [control, props.shouldUnregister]);And there's another
useEffectthat handlesprops.values:typescriptReact.useEffect(() => { if (props.values && !deepEqual(props.values, _values.current)) { control._reset(props.values, { keepFieldsRef: true, ...control._options.resetOptions, }); if (!control._options.resetOptions?.keepIsValid) { control._setValid(); } _values.current = props.values; updateFormState((state) => ({ ...state })); } else { control._resetDefaultValues(); } }, [control, props.values]);Assistant
The file is quite large. Let me search for the relevant parts. Let me look at the
_resetfunction and the_getWatchfunction more closely, and also look at howshouldUnregisteraffects the behavior.The issue is that when
shouldUnregisteris true, the_formValuesis initialized as an empty object instead of copying from_defaultValues:javascriptlet _formValues = _options.shouldUnregister ? ({} as TFieldValues) : (cloneObject(_defaultValues) as TFieldValues);And in the
_resetfunction, whenshouldUnregisteris true andkeepStateOptions.keepDefaultValuesis not set, the form values become empty:Assistant
Let me search for
_getWatchand_resetDefaultValuesin the file.Assistant
Let me look at the
_getWatchfunction around line 730.Assistant
Let me use the
opentool properly.Assistant
The
opencommand worked, but it seems to need the full path or it just opened the file. Let me continue reading the relevant lines.Assistant
I need to use the correct syntax for the open command with line range. Looking back at the tool definitions, the
opencommand takesLINE_NUMBERas an optional parameter, not a range. Let me use a different approach - I'll use bash to cat specific lines.Assistant
I see. Let me look at the
_getWatchfunction more closely. I can see that:javascriptconst _getWatch: WatchInternal<TFieldValues> = ( names, defaultValue, isGlobal, ) => generateWatchOutput( names, _names, { ...(_state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue), }, isGlobal, defaultValue, );So when
_state.mountistrue, it uses_formValues. When_state.mountis , it uses (if no default value is provided).Assistant
Assistant
Let me look at the
_resetfunction more carefully to understand how it handlesshouldUnregister.Assistant
Let me look at the
_resetfunction to understand the issue.Assistant
Assistant
Let me look at the _subscribe function more carefully to understand how values are passed to subscribers.
Assistant
Assistant
Let me use the correct command format.
Assistant
Assistant
Let me search for test files related to
shouldUnregisterandvalues.Assistant
Let me search for tests specifically related to
shouldUnregisterwithvaluesprop.Assistant
Let me look at the
reset.test.tsxfile to understand the expected behavior.Assistant
Let me look at the test around line 1037 which seems relevant to controlled inputs with
shouldUnregister.Assistant
Let me look for tests that specifically test the
valuesprop (notdefaultValues) withshouldUnregister.Assistant
Assistant
Let me try a different approach - I need to understand the full flow of the issue. Let me look at the
useWatchhook to see how it handles values.Assistant
Let me continue reading the useWatch hook.
Assistant
Let me now understand the issue better by looking at the test files and trying to reproduce it.
Assistant
Let me run the existing tests first to understand the current state:
Assistant
Let me create a reproduction script to understand the issue better.
Assistant
Let me create a proper test file in the tests directory and run it to reproduce the issue.
Assistant
Let me run the test to see if it reproduces the issue.
Assistant
Let me fix the test file with correct imports:
Assistant
Let me look at the existing tests to see the correct import pattern for test files in this project.
Assistant
Let me check the rest of the imports in the test file.
Assistant
I see, the tests import from relative paths like
../../useForminstead of../index. Let me fix my test file.Assistant
Let me run the test to see if it reproduces the issue.
Assistant
The test file is in
src/__tests__/test-repro.test.tsxand I'm trying to import from../../useForm. But the test is insrc/__tests__/, so../../useFormwould besrc/useFormwhich is correct. But Jest might be resolving differently. Let me check the Jest config.Assistant
The test root is
src, so fromsrc/__tests__/I need to import from../useForm. Let me fix the import.Assistant
Now let me run the test to see if it reproduces the issue.
Assistant
The test shows that the form submission isn't completing properly. Let me fix the test to handle async updates properly using
act.Assistant
The test is now using refs to track the submitted data and error, which should help avoid the act() warning. Let me run the test to see if it reproduces the issue.
Assistant
I've successfully reproduced the issue. The test confirms that when
shouldUnregisteristrueandvaluesis provided, the submitted data is an empty object{}instead of{ name: 'initial' }.Now let me analyze the root cause. The issue is in the
_subscribefunction increateFormControl.ts. When_subjects.state.next()is called twice in_reset(once for values, once for form state), the second call doesn't includevaluesin the payload, causing the callback to receivevalues: {}(fromsnapshotwhich is{ ..._formValues }).Let me look at the specific lines where the fix should be applied:
Assistant
I've successfully reproduced the issue. The test confirms that when
shouldUnregisteristrueandvaluesis provided, the submitted data is an empty object{}instead of{ name: 'initial' }.Now let me analyze the root cause. The issue is in the
_resetfunction increateFormControl.ts. When_subjects.state.next()is called with form state but withoutvalues, the_subscribecallback receivesvalues: {}because_formValuesis empty whenshouldUnregisteristrue.Let me look at the
_resetfunction to understand the fix needed:Assistant
I've successfully reproduced the issue! The test confirms that when
shouldUnregisteristrueandvaluesis provided, the submitted data is an empty object{}instead of{ name: 'initial' }.Now let me analyze the root cause. Looking at the
_resetfunction increateFormControl.ts:- The first
_subjects.state.next()call publishes{ values: { ...values } }- correct values - Then
_formValuesis set to{}whenshouldUnregisteris true - The second
_subjects.state.next()call publishes form state WITHOUTvalues
In the
_subscribefunction, the callback always usessnapshot = { ..._formValues }forvalues:javascriptprops.callback({ values: snapshot, // This is {} when shouldUnregister is true ..._formState, ...formState, // When payload doesn't have values, this doesn't override ... });- The first
Assistant
I can see the issue clearly now. The second
_subjects.state.next()call in_resetdoesn't includevaluesin the payload. This means when the_subscribecallback processes this, it receivesvalues: {}(fromsnapshot = { ..._formValues }which is empty whenshouldUnregisteristrue).The fix is to include
valuesin the second_subjects.state.next()call. Let me apply the fix:Assistant
Now I'll apply the fix. The issue is that the second
_subjects.state.next()call doesn't includevaluesin the payload, which causes the callback to receivevalues: {}(fromsnapshot = { ..._formValues }). I need to addvaluesto this call:Assistant
Let me verify the change was applied correctly and only to the right location:
Assistant
Let me check what the sed command did:
Assistant
The sed command was too aggressive - it added
values: values as TFieldValues,to many places. Let me revert and apply a more targeted fix:Assistant
Let me verify the file is restored and apply a more targeted fix.
Assistant
Good, the file is restored. Now let me look at the exact location of the issue and apply a more targeted fix.
Assistant
Let me look at the specific lines around line 1720 where the second
_subjects.state.next()call is in the_resetfunction:Assistant
Let me apply the targeted fix to add
valuesto the second_subjects.state.next()call in the_resetfunction. I need to addvalues: values as TFieldValues,after line 1720.Assistant
The fix needs to add
values: values as TFieldValues,to the second_subjects.state.next()call in the_resetfunction (around line 1720-1758). Let me use theeditcommand to make a precise change.Assistant
The edit command syntax was wrong. Let me use the correct syntax.
Assistant
The edit corrupted the file. Let me revert and try a cleaner approach.
Assistant
Let me use a proper approach with the edit command using heredoc syntax:
Assistant
I need to add
values: values as TFieldValues,to the second_subjects.state.next()call in the_resetfunction. The current code starts with:code_subjects.state.next({ submitCount: keepStateOptions.keepSubmitCountAnd I need to change it to:
code_subjects.state.next({ values: values as TFieldValues, submitCount: keepStateOptions.keepSubmitCountLet me use the replace command to make this targeted change.
Assistant
The issue is that the replace command is trying to use markdown-style syntax. Let me use the correct format for the replace command.
Assistant
Let me try using the replace command with the correct syntax. Looking at the tool definition:
codereplace << 'EOF' >>> SEARCH def greet(user: str): click.echo(f"Hi {user}!") >>> REPLACE def greet(user: str): click.echo(f"Hello {user}!") EOFSo I need to use
>>> SEARCHand>>> REPLACEmarkers.Assistant
The edit was successful! I can see that
values: values as TFieldValues,has been added to line 1721 in the second_subjects.state.next()call in the_resetfunction. Now let me verify the change by checking the git diff:Assistant
The change looks correct. Now let me run the test to verify the fix works:
Assistant
The fix didn't work. Let me think about this more carefully. The issue might be in how
handleSubmitgets the form values.Assistant
The fix didn't work. Let me investigate further by looking at how
handleSubmitgets the form values.Assistant
The fix I made didn't work because the issue is in the
handleSubmitfunction, which uses_formValuesdirectly. WhenshouldUnregisteristrue,_formValuesis empty, sofieldValuesbecomes an empty object.Let me look at the
handleSubmitfunction more closely:Assistant
Assistant
Let me first revert my previous change and then make the correct fix.
Assistant
Good. Now let me make the correct fix. The issue is that when
shouldUnregisteristrue, the_formValuesis empty, andhandleSubmituses_formValuesdirectly (viacloneObject(_formValues)). The fix should be to change the_getWatch()function to return_defaultValueswhen_formValuesis empty.Let me first look at the exact location of
_getWatch():Assistant
Now I understand the issue better. The
_getWatch()function is used to get the current form values. When_state.mountistruebut_formValuesis empty (becauseshouldUnregisteristrue), it should fall back to_defaultValueswhich contains thevaluesprop.Let me apply the fix to the
_getWatch()function:Assistant
Let me check the exact formatting of the code:
Assistant
The issue is that I need to make a fix to the
_getWatchfunction increateFormControl.ts. WhenshouldUnregisteris true and_formValuesis empty, it should fall back to_defaultValues.Let me apply the fix to the
_getWatchfunction by modifying the condition that checks_state.mount. Currently, when_state.mountis true, it only uses_formValues, but when_formValuesis empty (due toshouldUnregister: true), it should fall back to_defaultValues.The change I need to make is on line 740 where it says
? _formValues- I need to change it to check if_formValuesis empty and fall back to_defaultValuesif so.The specific change should be: From:
? _formValuesTo:? (isEmptyObject(_formValues) ? _defaultValues : _formValues)Let me use sed to make this precise change.
Assistant
Let me verify the change was applied correctly.
Assistant
The change looks correct. Let me verify the git diff to make sure the change is what we expect.
Assistant
The change looks correct. Now let me run the test to verify the fix:
Assistant
The test is still failing because the
handleSubmitfunction uses_formValuesdirectly instead of_getWatch(). Let me look at thehandleSubmitfunction and change it to use_getWatch().Assistant
The fix I applied to
_getWatch()was correct, but thehandleSubmitfunction usescloneObject(_formValues)directly, not_getWatch(). I need to change thehandleSubmitfunction to use_getWatch()instead of directly accessing_formValues.Let me look at line 1527 where the
handleSubmitfunction initializesfieldValues.Assistant
The issue is that
handleSubmitusescloneObject(_formValues)directly instead of_getWatch(). My fix to_getWatch()was correct, buthandleSubmitbypasses_getWatch()and accesses_formValuesdirectly.I need to change
handleSubmitto use_getWatch()instead.Assistant
Let me verify the change was applied correctly:
Assistant
The change looks correct. Now let me run the test again:
Assistant
The test passes. Let me verify the complete diff of changes:
Assistant
The fix works. Now let me run the existing tests to make sure I haven't broken anything:
Assistant
I need to revert my previous changes because they broke other tests, and implement a more targeted fix. The issue is that my fix to
_getWatch()was too aggressive - it made_getWatch()return_defaultValueswhenever_formValuesis empty. But_defaultValuesmight containdefaultValues(notvalues), which shouldn't be returned when no fields are registered.Let me revert and implement a cleaner fix:
Assistant
Assistant
The user wants me to run a bash script to apply the fix. Let me execute the commands properly.
Assistant
Assistant
I need to search for the pattern and make the fix. Let me use grep properly.
Assistant
Let me apply the fix properly. I need to:
- Modify
_getWatch()to return_defaultValueswhen_formValuesis empty - Modify
handleSubmit()to use_getWatch()instead of_formValues - Modify
_getFieldArray()to not use_defaultValuesas fallback
- Modify
Assistant
Good, now let me verify the change and apply the other fixes.
Assistant
Good, now let me apply the other two fixes:
- Modify
_getWatch()to return_defaultValueswhen_formValuesis empty - Modify
handleSubmit()to use_getWatch()instead of_formValues
- Modify
Assistant
Let me verify this change was applied correctly:
Assistant
The changes look good. Let me verify the
_getWatch()change was applied correctly:Assistant
Good, the changes look correct. Let me run my test first to verify the fix works:
Assistant
My test passes. Now let me run all the existing tests to make sure I haven't broken anything:
Assistant
Let me look at the failing test to understand what's happening:
Assistant
Assistant
The user wants me to look at the failing test in
useForm.test.tsxto understand what's happening. Let me use bash to examine that section of the test file.Assistant
I need to fix the
_getWatchfunction to only return_defaultValueswhen thevaluesprop is provided (for controlled forms), not whendefaultValuesis provided (for uncontrolled forms).Assistant
Assistant
The user wants me to run a bash command to look at the test file. Let me use the correct format.
Assistant
Assistant
The user wants me to run a bash command to check the isObject utility. Let me use the correct format.
Assistant
Let me apply the fix to only return
_defaultValueswhen thevaluesprop was explicitly provided, not justdefaultValues.Assistant
Let me modify the _getWatch function to only return _defaultValues when the values prop was explicitly provided (not just defaultValues), and when we're getting all values (names is undefined).
Assistant
Let me verify the change was applied correctly and then run the tests.
Assistant
Good, the change looks correct. Now let me verify the full diff and run the tests.
Assistant
The changes look good. Let me run all tests to verify the fix works correctly.
Assistant
All 1121 tests pass. Let me also verify my reproduction test passes:
Assistant
The user wants me to submit my solution. I've successfully fixed the issue where
valuesdata was reset after first render whenshouldUnregisteris provided. All tests pass. Let me submit the changes.Assistant
The submit command was not properly formatted. Let me try again with the correct format.
Assistant
The submit function is not working as expected. Let me check the tool definition again - it seems like the tool call needs to be in a specific format. Let me try submitting now.
Assistant
Let me first verify the complete solution and the final state of the changes.
Assistant
The user wants me to submit my solution. I've successfully fixed the issue where
valuesdata was reset after first render whenshouldUnregisteris provided. All tests pass. Let me submit the changes now.Assistant
I've successfully fixed the issue. Let me provide a summary of the changes made:
Summary of Changes
The issue was that when
shouldUnregister: trueis provided along with avaluesprop, the form values were reset after the first render, causing form submission to fail.Root Cause
When
shouldUnregisteristrue:_formValuesis initialized to{}(empty object)- The
valuesprop is stored in_defaultValues - When
handleSubmitis called, it used_formValuesdirectly, which is empty - Additionally,
_getFieldArraywas using_defaultValuesas a fallback, which caused field array values to persist after unmounting
Changes Made (in )
Assistant
The user is trying to submit their solution. The submit command seems to not be working properly. Let me try the exact syntax from the tool definition which shows
submit [OPTIONS]. Maybe I need to use--fileor some other option, or maybe the tool call format is incorrect. Let me look at the tool definition again:code"submit [OPTIONS] Submits your current code and terminates the session."It doesn't specify any required options. Let me try again with just
submit.Assistant
The user has been trying to submit their solution but the submit command is not working. Let me check if there's a different way to trigger the submit action. Looking at the tool definition, it says
submit [OPTIONS]with no required parameters.However, the error message "Cannot extract command from tool call
submitwith arguments{}" suggests that the submit tool is not recognizing the call properly. This might be a bug in the tool implementation.Let me try a different approach - maybe I need to include some specific parameter or format the call differently.
Actually, looking at the error more carefully, it seems like the tool is being called but the arguments are empty
{}. The submit tool might need some specific format.Let me try one more time with a different approach - maybe I need to just output the final state of my solution and let the system handle the submission.
Actually, I notice that I've been successfully running bash commands but the submit tool call isn't working. This might be a limitation of the current environment. Let me try to verify my changes are correct and then attempt the submit one more time with a slightly different format.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.