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 start by exploring the repository structure to understand the codebase and then find the issue related to
shouldUnregisterandvaluesdata being reset after first render.Assistant
Let me look at the
useForm.tsfile since the issue is related tovaluesdata being reset whenshouldUnregisteris provided. This seems to be the main hook that handles form values.Assistant
Now let me look at the
createFormControlfunction in the logic folder to understand howshouldUnregisteris handled:Assistant
Let me read the
createFormControl.tsfile to understand howshouldUnregisteris handled:Assistant
The file is large and was truncated. Let me see the key parts related to
shouldUnregisterand values being reset. Let me search for the specific parts that handlevaluesandshouldUnregister:<tool_call> <function=bash_terminal> <parameter=command> grep -n "shouldUnregister" src/logic/createFormControl.ts </tool_call>
Assistant
Let me search for
shouldUnregisterin the file to find the relevant code sections.Assistant
Let me look at the lines around 1677 where
_formValuesis set, and also around line 158 where_formValuesis initially set:<tool_call> <function=bash_terminal> <parameter=command> sed -n '155:165p' src/logic/createFormControl.ts </tool_call>
Assistant
The tool call wasn't made correctly. Let me try using bash_terminal instead with proper command syntax.
Assistant
Good. Now let me look at lines around 1677 where
_formValuesis set during reset.Assistant
Now let me look at the
useForm.tsfile again to see how thevaluesprop is handled. I saw earlier that there's auseEffectthat handlesprops.values. Let me look at that section more closely.<tool_call> <function=bash_terminal> <parameter=command> sed -n '105:130p' src/useForm.ts </tool_call>
Assistant
The error message indicates the tool wasn't called. Let me try again with bash_terminal for the sed command.
Assistant
Let me look at a larger range to find the
useEffectthat handlesprops.values.Assistant
Now I can see the issue. Let me look at the effect that handles
props.values:React.useEffect(() => { if (props.values && !deepEqual(props.values, _values.current)) { control._reset(props.values, { keepFieldsRef: true, ...control._options.resetOptions, });Assistant
Let me look at the
_resetfunction to understand its full implementation.Assistant
Now I can see the issue! In the
_resetfunction (line 1677-1681):_formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);When
shouldUnregisteris true andkeepDefaultValuesis not true,_formValuesis set to{}. This is the bug. Whenprops.valuesis provided to the form andshouldUnregisteris true, the values should be preserved, not cleared to{}.The fix should preserve the
values(which is the clonedformValuesor_defaultValues) whenshouldUnregisteris true, instead of clearing it to{}.Let me now look at the test files to understand how the existing tests work:
<tool_call> <function=bash_terminal> <parameter=command> ls src/tests/ </tool_call>
Assistant
Let me try again with the proper bash_terminal tool to list the test files.
Assistant
Let me look at the
useForm.test.tsxfile to understand how tests are structured and to find existing tests related toshouldUnregisterandvalues:Assistant
Let me look at the test cases around
shouldUnregisterandvalues:Assistant
The command failed because grep returned no results. Let me search differently.
<tool_call> <function=bash_terminal> <parameter=command> grep -n "shouldUnregister" src/tests/useForm.test.tsx </tool_call>
Assistant
The command failed. Let me try again with the bash_terminal tool properly.
Assistant
Now let me look at the section where
_formValuesis set in the_resetfunction more closely:Assistant
Let me understand the issue better. Looking at the code:
- Line 158-160: When
shouldUnregisteris true,_formValuesis initialized to{} - Line 1677-1681: In
_reset, whenshouldUnregisteris true andkeepDefaultValuesis not true,_formValuesis set to{}again - Line 1683-1686: But
_subjects.state.nextcorrectly sends{ ...values }as the new values
The issue is that
_formValuesis set to{}when it should preserve the actual values. Let me check what_formValuesis used for:- Line 158-160: When
Assistant
Let me look at line 1576 to see how
_formValuesis used in the_getWatchmethod.Assistant
Let me find the
_getWatchmethod:Assistant
Let me look at the _getWatch method implementation.
Assistant
Now I see the issue. Looking at the
_getWatchmethod (lines 730-749), when_state.mountis true, it uses_formValues. Otherwise, it uses_defaultValuesordefaultValue.The issue is that when
shouldUnregisteris true:_formValuesis initialized to{}- In , when is not true, is set to even though contains the correct data
Assistant
The tool call wasn't made. Let me try again with the proper bash_terminal command.
Assistant
Looking at line 1628, there is a
keepStateOptions.keepValuescheck. Let me look at the context around that line to understand howkeepValuesis handled.Assistant
Now I understand the issue. Looking at lines 1677-1681:
_formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);When
shouldUnregisteris true andkeepDefaultValuesis not true,_formValuesis set to{}. This is incorrect because:- The
valuesvariable contains the correct values passed to
- The
Assistant
Let me try again with the proper bash_terminal command to view the test cases.
Assistant
Let me now understand the issue better. Let me create a test script to reproduce the issue:
<tool_call> <function=bash_terminal> <parameter=command> cat package.json | grep -A 10 '"scripts"' </tool_call>
Assistant
The tool call wasn't made. Let me try again with the proper bash_terminal command.
Assistant
Now I understand the issue. Let me look at the fix needed in the
_resetfunction. The problem is on lines 1677-1681 increateFormControl.ts:_formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);When
shouldUnregisteris true,_formValuesis set to{}instead of preserving thevalues. This is incorrect because:- When
props.valuesis provided to the form, the values should be preserved in_formValues - The
_subjects.state.next({ values: { ...values } as TFieldValues })already correctly sends the values to subscribers _getWatchuses_formValuesto return the current values, so if_formValuesis{}, the watched values will be empty
The fix should preserve the
valueswhenshouldUnregisteris true:- When
Assistant
I see the issue clearly now. The fix should be to change line 1681 from
({} as TFieldValues)to(cloneObject(values) as TFieldValues). This will preserve the values whenshouldUnregisteris true.Let me first run the existing tests to see if they pass:
Assistant
Let me try using npm test directly:
Assistant
Let me try a different approach:
Assistant
Good, the existing tests pass. Now let me look at the issue more closely. Let me check if there are tests related to
props.valueswithshouldUnregister:Assistant
No tests found for
valueswithshouldUnregister. Let me look at the test forprops.values:Assistant
Let me look at this test to understand how
props.valuesis expected to work:Assistant
Let me see the rest of this test:
Assistant
Now I understand the issue. When
shouldUnregister: trueis set andprops.valuesis provided, the_formValuesis incorrectly set to{}instead of preserving the values. Let me make the fix:Assistant
Now I understand the issue. The fix should change the line that sets
_formValueswhenshouldUnregisteris true. Instead of setting it to{}, it should preserve the actualvaluesthat were passed to_reset.Let me apply the fix:
Assistant
Let me fix the sed command by escaping the special characters properly.
Assistant
Let me verify the change:
Assistant
The sed command didn't work because the pattern didn't match. Let me try a different approach using the
openandeditcommands:Assistant
Let me use the
editcommand to fix the issue.Assistant
Let me use the open command to open the file, then use edit to fix the issue.
Assistant
Let me try a different approach with the correct syntax for the open command:
Assistant
Now let me fix the issue by using the edit command:
Assistant
Now let me also check if there's a similar issue in the initialization of
_formValuesat the beginning of the function (line 158-160). Let me check that:Assistant
The initialization of
_formValuesat line 158-160 is different. WhenshouldUnregisteris true,_formValuesis initialized to . This is the initial state before any values are set.Assistant
Let me try running the tests again with the proper command.
Assistant
Good, the tests still pass. Let me run more tests to ensure my fix doesn't break anything:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="useForm.test" 2>&1 | tail -30 </tool_call>
Assistant
Let me run the test again with the proper bash_terminal command.
Assistant
All 70 tests pass. Now let me create a test case to reproduce the issue mentioned in the issue description to verify that my fix works:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="useForm.test" --testNamePattern="values" 2>&1 | tail -40 </tool_call>
Assistant
Let me run the tests again with the proper bash_terminal command.
Assistant
Let me create a test script to verify the fix works for the issue described. I'll create a test case that reproduces the problem:
Assistant
The test file wasn't found because it's in /tmp. Let me move it to the src/tests directory.
Assistant
The file moved but the path needs to be updated for the import. Let me fix that first.
Assistant
The import path is wrong. Let me fix it:
Assistant
Let me run the test again:
Assistant
The test passes! This confirms that my fix works. Now let me remove the test file since it was just for verification:
Assistant
Now let me run all the tests to make sure my fix doesn't break anything:
Assistant
One test failed. Let me look at the failing test to understand what it expects:
Assistant
The test expects the watched data to be:
{}(initial state){}(after shouldUnregister effect){ test: '1234' }(after reset)
But my fix causes the watched data to include both
testanddatain the third object. This is because theresetfunction is called with bothtestanddata, and my fix preserves both values.Looking at the test more carefully, I see that the test expects
{ test: '1234' }but not{ data: '1234' }. This is because the test only renders an input fortest, and expectsdatato be "unregistered" (not included in the watched values).The issue is that the test is expecting
shouldUnregister: trueto remove values from the watched results, not just from the form fields. But this is inconsistent with howshouldUnregisteris supposed to work - it should only unregister fields when they are unmounted, not clear all values.Let me look at the test more carefully to understand what behavior is expected:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '492,530p' src/tests/useForm/watch.test.tsx </tool_call>
Assistant
The command didn't run properly. Let me try again with the correct bash_terminal syntax.
Assistant
Looking at this test, I see that it expects
shouldUnregister: trueto exclude unregistered fields from the watched values. The test hasdata: '1234'in the reset values, but since there's no input registered fordata, it expects the watched values to not includedata.This is a nuanced behavior of
shouldUnregister: true. When a field is unregistered (not mounted), its value should not appear in the watched results. But when a field is registered (mounted), its value should appear.The issue is that my fix preserves ALL values in
_formValues, even for fields that are not registered. This is incorrect because the test expectsshouldUnregister: trueto exclude unregistered fields from the watched values.Let me think about this more carefully. The original issue description says:
Assistant
I need to look at the
_getWatchmethod to understand how it handles unregistered fields.Assistant
Let me look at the
generateWatchOutputfunction to understand how it filters out unregistered fields:<tool_call> <function=bash_terminal> <parameter=command> cat src/logic/generateWatchOutput.ts </tool_call>
Assistant
The command didn't run. Let me try again with the proper bash_terminal command.
Assistant
Assistant
I need to look at the reset function to understand how fields are registered. Let me try the sed command again.
Assistant
Assistant
The command didn't run properly. Let me try again with the correct bash_terminal command.
Assistant
I see my fix. Let me revert it and understand the test better.
<tool_call> <function=bash_terminal> <parameter=command> git checkout src/logic/createFormControl.ts </tool_call>
Assistant
Let me try running the test with the original code first to understand the expected behavior.
Assistant
The test is still failing even though I reverted my change. This means the test is already failing with the original code, which suggests the test might have been broken or the repository was in a different state.
Let me check if the test was passing before by checking the git status:
<tool_call> <function=bash_terminal> <parameter=command> git status </tool_call>
Assistant
Let me check the git status properly with the bash_terminal command.
Assistant
The test might have been failing before my changes. Let me restore the original code and check if the test was passing:
<tool_call> <function=bash_terminal> <parameter=command> git restore src/logic/createFormControl.ts package.json </tool_call>
Assistant
The command didn't run properly. Let me try with the bash_terminal command again.
Assistant
Now let me run the test with the original code to see if it passes:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="watch.test" --testNamePattern="should flush additional render for shouldUnregister: true" 2>&1 | tail -30 </tool_call>
Assistant
The tool call wasn't invoked. Let me try again with the proper bash_terminal syntax.
Assistant
Assistant
I need to look at the lines in createFormControl.ts to understand the current state and then implement the fix properly.
Assistant
Now I need to understand the issue better. The problem is that when
shouldUnregister: trueandprops.valuesis provided, the values should be preserved. But the current code sets_formValuesto{}whenshouldUnregister: true.However, the test that's failing shows that the expected behavior is that only registered fields should be included in the watched values when
shouldUnregister: true. This is a nuanced behavior.Let me look at the issue from a different angle. The issue is that when
props.valuesis provided:- The
useEffectinuseForm.tscallscontrol._reset(props.values, { keepFieldsRef: true, ... }) - In
_reset, whenshouldUnregister: true,_formValuesis set to{}
The fix should be to preserve the values for registered fields. When
keepFieldsRef: trueis passed, only mounted fields should have their values updated. So_formValuesshould only include values for mounted fields.Let me implement a fix that preserves values for mounted fields when
shouldUnregister: true:- The
Assistant
Now let me run the tests to see if this fix works:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="watch.test" --testNamePattern="should flush additional render for shouldUnregister: true" 2>&1 | tail -40 </tool_call>
Assistant
The tool call wasn't made properly. Let me try again with the correct bash_terminal syntax.
Assistant
The test passes! Now let me run all the tests to make sure my fix doesn't break anything else:
<tool_call> <function=bash_terminal> <parameter=command> npm test 2>&1 | tail -30 </tool_call>
Assistant
The tool call wasn't made properly again. Let me try the bash_terminal command again.
Assistant
All 1120 tests pass! Now let me create a test to verify that the original issue is fixed - that
valuesdata is preserved whenshouldUnregister: trueis provided:<tool_call> <function=bash_terminal> <parameter=command> cat > src/tests/test-shouldUnregister-values-fix.test.tsx << 'EOF' import React from 'react'; import { render, fireEvent, screen } from '@testing-library/react'; import { useForm } from '../useForm';
describe('shouldUnregister with values prop', () => { it('should preserve values when shouldUnregister is true', async () => { type FormValues = { firstName: string; };
function App() { const [submitCount, setSubmitCount] = React.useState(0); const [data, setData] = React.useState<FormValues | null>(null); const { register, handleSubmit, watch } = useForm<FormValues>({ shouldUnregister: true, values: { firstName: 'John', }, }); const formValues = watch(); const onSubmit = (data: FormValues) => { setData(data); setSubmitCount((prev) => prev + 1); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('firstName')} /> <p>watched: {formValues?.firstName}</p> <p>submitted: {data?.firstName}</p> <p>submitCount: {submitCount}</p> <button type="submit">Submit</button> </form> ); } render(<App />); // Check that the initial value is shown expect(screen.getByText('watched: John')).toBeInTheDocument(); // Submit the form fireEvent.click(screen.getByRole('button', { name: 'Submit' })); // Check that the submitted data contains the correct value await screen.findByText('submitted: John'); expect(screen.getByText('submitCount: 1')).toBeInTheDocument();Assistant
Let me run the bash_terminal command properly to create the test file.
Assistant
Now let me run the test to verify the fix works:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="test-shouldUnregister-values-fix" 2>&1 | tail -30 </tool_call>
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command.
Assistant
The test passes! Now let me remove the test file since it was just for verification:
<tool_call> <function=bash_terminal> <parameter=command> rm src/tests/test-shouldUnregister-values-fix.test.tsx </tool_call>
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to remove the test file.
Assistant
Good, the test file was removed. Now let me review my fix to make sure it handles edge cases correctly. Let me also check the initialization of
_formValuesat the beginning of the function.<tool_call> <function=bash_terminal> <parameter=command> sed -n '158,160p' src/logic/createFormControl.ts </tool_call>
Assistant
Let me try again with the bash_terminal command to view the initialization code.
Assistant
Assistant
Let me try with the bash_terminal command to edit the file.
Assistant
I need to update my fix to only include registered fields in
_formValueswhenshouldUnregister: trueandkeepFieldsRef: true. Let me modify the fix:<tool_call> <function=bash_terminal> <parameter=command> edit 1677:1687 << 'EOF' if (_options.shouldUnregister) { if (keepStateOptions.keepDefaultValues) { _formValues = cloneObject(_defaultValues) as TFieldValues; } else { if (keepStateOptions.keepFieldsRef) { const _formValuesWithMountedFields = {} as TFieldValues; for (const fieldName of Array.from(_names.mount)) { set(_formValuesWithMountedFields, fieldName, get(values, fieldName)); } _formValues = _formValuesWithMountedFields; } else { _formValues = {} as TFieldValues; } } } else { _formValues = cloneObject(values) as TFieldValues; } EOF </tool_call>
Assistant
The edit command wasn't invoked properly. Let me try again with the proper bash_terminal syntax to edit the file.
Assistant
Now let me run the tests to see if my updated fix works:
<tool_call> <function=bash_terminal> <parameter=command> npm test 2>&1 | tail -20 </tool_call>
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to run the tests.
Assistant
All 1120 tests pass! Let me now create a test to verify that the original issue is fixed - that
valuesdata is preserved whenshouldUnregister: trueis provided:<tool_call> <function=bash_terminal> <parameter=command> cat > src/tests/test-shouldUnregister-values-fix.test.tsx << 'EOF' import React from 'react'; import { render, fireEvent, screen } from '@testing-library/react'; import { useForm } from '../useForm';
describe('shouldUnregister with values prop', () => { it('should preserve values when shouldUnregister is true', async () => { type FormValues = { firstName: string; };
function App() { const [submitCount, setSubmitCount] = React.useState(0); const [data, setData] = React.useState<FormValues | null>(null); const { register, handleSubmit, watch } = useForm<FormValues>({ shouldUnregister: true, values: { firstName: 'John', }, }); const formValues = watch(); const onSubmit = (data: FormValues) => { setData(data); setSubmitCount((prev) => prev + 1); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('firstName')} /> <p>watched: {formValues?.firstName}</p> <p>submitted: {data?.firstName}</p> <p>submitCount: {submitCount}</p> <button type="submit">Submit</button> </form> ); } render(<App />); expect(screen.getByText('watched: John')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Submit' })); await screen.findByText('submitted: John'); expect(screen.getByText('submitCount: 1')).toBeInTheDocument();Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to create the test file.
Assistant
Now let me run the test to verify the fix works:
<tool_call> <function=bash_terminal> <parameter=command> npm test -- --testPathPatterns="test-shouldUnregister-values-fix" 2>&1 | tail -30 </tool_call>
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to run the test.
Assistant
The test passes! Now let me remove the test file and also test some edge cases to make sure my fix handles them correctly.
Let me first remove the test file:
Assistant
Let me also test the edge case where
shouldUnregister: trueis set and the values include fields that are not registered. My fix should only include registered fields in_formValues.Let me also check if there are any other places in the code that might need to be updated. Let me search for other usages of
shouldUnregisterin the codebase.Assistant
Let me check line 1352 and 1719 to see if there are any issues with the
_state.mountlogic that might be affected by my fix:<tool_call> <function=bash_terminal> <parameter=command> sed -n '1350,1360p' src/logic/createFormControl.ts </tool_call>
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to view the lines.
Assistant
This code looks fine. It's in the
unregisterfunction and it handles unregistered fields correctly.Let me also check line 1719 to understand the
_state.mountlogic:Assistant
Assistant
The tool call wasn't made properly again. Let me try with the bash_terminal command to view the lines.
Assistant
I see.
_defaultValuesis initialized toprops.values(orprops.defaultValues) when provided. So even if_getWatchreturns_defaultValues, the values should be correct.But there's still an issue. When
props.valuesis updated (via theuseEffectinuseForm.ts), theresetfunction is called with the new values. In theresetfunction,_defaultValuesis updated (unlesskeepDefaultValuesis true), and_formValuesis also updated.Let me trace through what happens when
props.valuesis updated:- Initial render:
_defaultValues = { firstName: 'John' },_formValues = {}(because )
- Initial render:
Assistant
The tool call wasn't invoked. Let me try again with the bash_terminal command to run the tests.
Assistant
All 1120 tests pass! My fix is working correctly. Let me now summarize what I've done:
-
Identified the issue: When
shouldUnregister: trueis provided along withprops.values, the values were being reset to{}after the first render. This happened because in the_resetfunction, whenshouldUnregisteris true,_formValueswas being set to{}instead of preserving the values for registered fields. -
Fixed the issue: Modified the
_resetfunction insrc/logic/createFormControl.tsto preserve values for registered fields whenshouldUnregister: trueandkeepFieldsRef: trueis passed. The fix ensures that:- When
keepDefaultValues: true,_formValuesis set tocloneObject(_defaultValues) - When
keepFieldsRef: true,_formValuesis set to only include values for registered fields (mounted fields) - Otherwise, is set to
- When
-
Assistant
The tool call wasn't invoked. Let me try with the bash_terminal command to show the git diff.
Assistant
Now let me verify that my fix handles all the edge cases correctly by reviewing the changes once more. Let me also make sure the code style matches the existing codebase.
Looking at the diff, the fix looks correct. Let me submit the changes:
<tool_call> <function=bash_terminal> <parameter=command> submit </tool_call>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.