Let me trace through the issue more carefully. The problem is:
-
When shouldUnregister: true is provided along with values, the values get reset after the first render.
-
Looking at useForm.ts:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
React.useEffect(() => {
if (props.values && !deepEqual(props.values, _values.current)) {
control._reset(props.values, {
keepFieldsRef: true,
...control._options.resetOptions,
});
// ...
}
}, [control, props.values]);
The key issue is:
- The
shouldUnregister effect runs BEFORE the values effect.
- The
shouldUnregister effect calls _subjects.state.next({ values: control._getWatch() }).
- This notifies subscribers, including the form state.
But wait, let me look at the shouldUnregister effect more carefully. It's in useForm.ts:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
This effect runs when control or props.shouldUnregister changes. On the first render:
control is stable (from the ref)
props.shouldUnregister is true
So this effect runs only once (on first render), and publishes _getWatch().
Then the values effect runs:
React.useEffect(() => {
if (props.values && !deepEqual(props.values, _values.current)) {
control._reset(props.values, {
keepFieldsRef: true,
...control._options.resetOptions,
});
// ...
}
}, [control, props.values]);
This calls _reset(props.values, { keepFieldsRef: true }).
Inside _reset:
-
_formValues = _options.shouldUnregister ? {} as TFieldValues : cloneObject(values)
- Since
shouldUnregister is true, _formValues = {}
-
Then _subjects.state.next({ values: { ...values } }) is called
-
But wait, the _formValues is reset to {} before this!
Actually, let me look at the order of operations in _reset:
if (!keepStateOptions.keepValues) {
// ...
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
So _formValues is set to {} (because shouldUnregister is true), and then _subjects.state.next({ values: { ...values } }) is called.
The _subjects.state.next call publishes the correct values (values which is props.values). But the subscribers might not use this value correctly.
Actually, let me look at the subscribe callback in useForm.ts:
useIsomorphicLayoutEffect(() => {
const sub = control._subscribe({
formState: control._proxyFormState,
callback: () =>
updateFormState({
...control._formState,
defaultValues:
control._defaultValues as FormState<TFieldValues>['defaultValues'],
}),
reRenderRoot: true,
});
// ...
}, [control]);
This callback calls updateFormState with control._formState, which doesn't include the values from the _subjects.state.next payload.
So the issue is that when _subjects.state.next({ values: { ...values } }) is called, the callback doesn't receive the values from the payload. It only reads control._formState and control._defaultValues.
But wait, the values in the payload is separate from _formState.values. So the form state doesn't include the values from the payload.
Hmm, let me think about this differently. The issue says "values data is reset after first render". This suggests that after the first render, the values become empty.
When the form is submitted, handleSubmit uses _formValues:
let fieldValues:
| TFieldValues
| TTransformedValues
| Record<string, never> = cloneObject(_formValues);
So if _formValues is {}, then the submitted data is empty.
Now, when is _formValues set to {}?
-
In createFormControl, _formValues is initialized:
let _formValues = _options.shouldUnregister
? ({} as TFieldValues)
: (cloneObject(_defaultValues) as TFieldValues);
Since shouldUnregister is true, _formValues = {}.
-
In _reset, _formValues is set to {}:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
So after _reset is called with keepDefaultValues: false, _formValues is {}.
But the values effect calls _reset(props.values, { keepFieldsRef: true }). And inside _reset:
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
So if keepFieldsRef is true, setValue is called for each field in _names.mount. This should populate _formValues with the values.
But wait, when _reset is called for the first time, _names.mount is empty (no fields are registered yet). So the loop doesn't do anything.
Let me trace through the full flow:
-
createFormControl(props) is called:
_defaultValues = cloneObject(props.values) (because props.values is provided)
_formValues = {} (because shouldUnregister is true)
-
In useForm:
- The
shouldUnregister effect runs: _subjects.state.next({ values: control._getWatch() })
_getWatch() returns from _defaultValues (since _state.mount is false)
_defaultValues has the values from props.values
-
The values effect runs: _reset(props.values, { keepFieldsRef: true })
_defaultValues = updatedValues (clone of props.values)
keepFieldsRef is true, but _names.mount is empty, so no setValue calls
_formValues = {} (because shouldUnregister is true and keepDefaultValues is not passed)
_subjects.state.next({ values: { ...values } }) is called
_subjects.state.next({ submitCount: 0, ... }) is called
-
User interacts with the form (registers fields):
register('name') is called
updateValidAndValue('name', true, options.value) is called
- Since
shouldSkipSetValueAs is true:
const defaultValue = get(
_formValues,
'name',
isUndefined(value) ? get(_defaultValues, 'name') : value,
);
// defaultValue = _defaultValues['name'] = 'test'
set(_formValues, 'name', defaultValue);
// _formValues['name'] = 'test'
-
User submits the form:
handleSubmit uses cloneObject(_formValues)
_formValues should have { name: 'test', email: 'test@example.com' }
So in theory, the form should submit correctly. But the issue says the values are reset after the first render.
Wait, let me re-read the issue:
values data is reset after first render, when shouldUnregister is provided
Maybe the issue is that when the form re-renders (due to state updates from effects), the values are reset.
Let me look at the shouldUnregister effect again:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
Wait, the dependencies are [control, props.shouldUnregister]. But control is an object from createFormControl, and props.shouldUnregister is true. These shouldn't change between renders.
But what about subsequent renders? If the component re-renders (e.g., due to state updates), the effects don't re-run unless the dependencies change.
Hmm, but wait. Let me look at the values effect:
React.useEffect(() => {
if (props.values && !deepEqual(props.values, _values.current)) {
control._reset(props.values, {
keepFieldsRef: true,
...control._options.resetOptions,
});
// ...
} else {
control._resetDefaultValues();
}
}, [control, props.values]);
The dependencies are [control, props.values]. If props.values is the same reference, the effect doesn't re-run. But if props.values is a new object, the effect re-runs.
In a typical React component, if props.values is created inline (e.g., { name: 'test', email: 'test@example.com' }), it's a new object on every render. So the effect would re-run on every render.
But wait, the deepEqual check compares the old value with the new value. If they're the same, the else branch runs:
} else {
control._resetDefaultValues();
}
And _resetDefaultValues is:
const _resetDefaultValues = () =>
isFunction(_options.defaultValues) &&
(_options.defaultValues as Function)().then((values: TFieldValues) => {
reset(values, _options.resetOptions);
_subjects.state.next({
isLoading: false,
});
});
This only does something if _options.defaultValues is a function. In the issue, the user passes values but not defaultValues. So _options.defaultValues is probably undefined, and _resetDefaultValues does nothing.
Hmm, but what if _options.defaultValues is set to something else?
Actually, wait. Let me re-read the issue. The user says:
- Simply submit a form
- See error
So the user renders a form, then submits it, and sees an error. The error is probably that the submitted data is empty or wrong.
Let me think about what could cause the values to be reset between the initial render and the submit.
Actually, I just realized something. Let me look at the shouldUnregister effect:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
This effect runs when control or props.shouldUnregister changes. But wait, control is from _formControl.current.control. On the first render, _formControl.current is undefined, so createFormControl is called. On subsequent renders, _formControl.current is already set, so control is the same object.
But the effect might run on subsequent renders if the effect dependencies change. Let me think...
Actually, React hooks don't re-run just because the component re-renders. They only re-run if the dependencies change.
But wait! The control object is stored in a ref. So it doesn't change between renders. And props.shouldUnregister is a boolean. If the user passes shouldUnregister: true, it's true on every render.
So the shouldUnregister effect should only run once (on first render).
Hmm, but what about the values effect? Its dependencies are [control, props.values]. If props.values is a new object on every render (e.g., { name: 'test', email: 'test@example.com' }), then the effect re-runs on every render.
And on the second render:
_values.current is already set to the original props.values
- If the new
props.values has the same content (but is a different object), deepEqual returns true
- So the
else branch runs: control._resetDefaultValues()
And _resetDefaultValues only does something if _options.defaultValues is a function. So it should do nothing.
Unless... wait, what if the user passes both values and defaultValues? Or what if defaultValues is set somewhere else?
Actually, let me re-read the code:
let _options = {
...defaultOptions,
...props,
};
So _options is a merge of defaultOptions and props. If the user passes values but not defaultValues, then _options.defaultValues is undefined.
And _resetDefaultValues only does something if _options.defaultValues is a function. So it should do nothing.
Hmm, I'm stuck. Let me try a different approach. Let me look at the GitHub issue or the codesandbox to understand the exact reproduction steps.
Actually, I don't have access to the codesandbox. But the issue says "values data is reset after first render". Let me think about what "after first render" means.
Maybe "after first render" means after the first effect runs. And the issue is that the shouldUnregister effect runs BEFORE the values effect, and the shouldUnregister effect somehow resets the values.
Wait, let me look at the shouldUnregister effect again:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
This calls _subjects.state.next({ values: control._getWatch() }). And _getWatch() returns the values from _defaultValues (since _state.mount is false).
But _defaultValues has the values from props.values (because it was set in createFormControl). So _getWatch() should return the correct values.
Unless... wait, what if _defaultValues is undefined or empty?
Let me look at createFormControl again:
let _defaultValues =
isObject(_options.defaultValues) || isObject(_options.values)
? cloneObject(_options.defaultValues || _options.values) || {}
: {};
So _defaultValues is set to cloneObject(_options.defaultValues || _options.values) if either is an object. Otherwise, it's {}.
If the user passes values: { name: 'test' }, then _defaultValues = cloneObject({ name: 'test' }).
So _defaultValues should have the correct values.
Hmm, but wait. Let me look at the values effect again:
React.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]);
On the first render:
_values.current is undefined
props.values is { name: 'test' }
deepEqual({ name: 'test' }, undefined) is false
- So
_reset(props.values, { keepFieldsRef: true }) is called
Inside _reset:
_defaultValues = cloneObject(props.values) = { name: 'test' }
keepFieldsRef is true, but _names.mount is empty, so no setValue calls
_formValues = {} (because shouldUnregister is true)
But wait, _subjects.state.next({ values: { ...values } }) is called. So the subscribers receive the correct values.
Hmm, but the issue says the values are reset. Maybe the issue is with how the values are read during submission?
Actually, let me look at handleSubmit again:
let fieldValues:
| TFieldValues
| TTransformedValues
| Record<string, never> = cloneObject(_formValues);
So handleSubmit uses cloneObject(_formValues). And _formValues is {} after _reset.
But then the user registers fields (by rendering inputs with register), and updateValidAndValue is called, which sets _formValues[name] = defaultValue.
So after fields are registered, _formValues should have the values.
Unless the user doesn't render any inputs? But that doesn't make sense. The user "simply submits a form", which implies there are inputs.
OK let me try a different approach. Let me look at the actual test cases in the repository to understand the expected behavior.
Actually, wait. Let me re-read the issue:
values data is reset after first render, when shouldUnregister is provided
Maybe "reset" means something different. Maybe the values are set correctly initially, but then they become empty after the form re-renders.
Let me think about when the form re-renders:
- After effects run (which call
_subjects.state.next)
- After user interacts with inputs
- After parent component re-renders
If the parent component re-renders with a new props.values object (even if the content is the same), the values effect re-runs:
if (props.values && !deepEqual(props.values, _values.current)) {
// ...
} else {
control._resetDefaultValues();
}
If props.values has the same content as _values.current, deepEqual returns true, so the else branch runs.
But wait! What if props.values is undefined on a subsequent render? This could happen if the parent component passes a temporary state that's undefined initially.
In the test case I found earlier:
function Loader() {
const [values, setValues] = React.useState<FormValues>({
test: '',
test1: '',
});
// ...
return <App values={values} />;
}
const App = ({ values }: { values: FormValues }) => {
const { register } = useForm({
values,
});
// ...
};
So values starts as { test: '', test1: '' } and is loaded asynchronously. If the user passes { test: '', test1: '' } initially and then { test: 'test', test1: 'data' } later, the values effect would re-run.
But this is a different issue. The issue in question is about shouldUnregister.
OK let me try yet another approach. Let me look at the shouldUnregister effect:
React.useEffect(() => {
props.shouldUnregister &&
control._subjects.state.next({
values: control._getWatch(),
});
}, [control, props.shouldUnregister]);
Wait, I just noticed something. The effect has control as a dependency. But control is the object from createFormControl, which is stable. So the effect should only run once.
But what if the effect re-runs on a subsequent render? This could happen if:
control changes (but it's stored in a ref, so it shouldn't)
props.shouldUnregister changes (e.g., from undefined to true)
If props.shouldUnregister changes from undefined to true, the effect re-runs. And _subjects.state.next({ values: control._getWatch() }) is called.
But this should set the values correctly, not reset them.
Hmm, I'm still stuck. Let me look at the _getWatch function more carefully.
Actually, wait! I just realized something. The _getWatch function returns values based on _formValues (if _state.mount is true) or _defaultValues (if _state.mount is false).
On the first render:
_state.mount is false (it's set to true in a later effect)
_getWatch() returns from _defaultValues
_defaultValues has the values from props.values
But after the values effect runs:
_reset is called
- Inside
_reset, _state.mount is set:
_state.mount =
!_proxyFormState.isValid ||
!!keepStateOptions.keepIsValid ||
!!keepStateOptions.keepDirtyValues ||
(!_options.shouldUnregister && !isEmptyObject(values));
- Since
shouldUnregister is true and values is not empty, _state.mount is false (because !_options.shouldUnregister is false)
So _state.mount remains false. And _getWatch() continues to return from _defaultValues.
Hmm, but what if the shouldUnregister effect re-runs on a subsequent render?
Wait, the effect dependencies are [control, props.shouldUnregister]. If neither changes, the effect doesn't re-run. So the shouldUnregister effect should only run once.
OK let me try yet another approach. Let me look at the handleSubmit function and see how it collects values.
const handleSubmit: UseFormHandleSubmit<TFieldValues, TTransformedValues> =
(onValid, onInvalid) => async (e) => {
let fieldValues:
| TFieldValues
| TTransformedValues
| Record<string, never> = cloneObject(_formValues);
// ...
};
So handleSubmit uses cloneObject(_formValues). And _formValues is set to {} after _reset with shouldUnregister is true.
But if the user renders inputs with register, the fields are registered and their values are set in _formValues via updateValidAndValue.
Unless... wait, what if the fields are registered AFTER _reset is called?
Let me trace through the full flow again:
-
createFormControl(props) is called:
_defaultValues = cloneObject(props.values) = { name: 'test' }
_formValues = {} (because shouldUnregister is true)
-
Component renders:
- Inputs are created with
register('name')
register('name') is called
updateValidAndValue('name', true, options.value) is called
_formValues['name'] = _defaultValues['name'] = 'test'
-
Effects run:
shouldUnregister effect: _subjects.state.next({ values: control._getWatch() })
_getWatch() returns { name: 'test' } (from _defaultValues)
values effect: _reset(props.values, { keepFieldsRef: true })
_defaultValues = cloneObject(props.values) = { name: 'test' }
_names.mount contains ['name'], so setValue is called:
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
// setValue('name', 'test')
_formValues = {} (because shouldUnregister is true and keepDefaultValues is not passed)
Wait, so setValue is called BEFORE _formValues is reset to {}. Let me check the order of operations in _reset:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
// ...
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
// ...
}
So the order is:
setValue is called for each field in _names.mount
_formValues is set to {}
So setValue is called BEFORE _formValues is reset. And setValue('name', 'test') should set _formValues['name'] = 'test'.
Wait, but setValue sets the value in _formValues:
const _setValue = ... => {
// ...
if (!isValueUnchanged) {
set(_formValues, name, cloneValue);
}
// ...
};
So setValue('name', 'test') sets _formValues['name'] = 'test'. Then _formValues is set to {}, which overwrites the previous value.
So after _reset, _formValues is {}. And the value 'test' that was set by setValue is lost.
But wait, the user registers the input BEFORE the effect runs. So the flow is:
-
Component renders:
- Input with
register('name') is created
register('name') is called
updateValidAndValue('name', true, undefined) is called
_formValues['name'] = _defaultValues['name'] = 'test'
-
Effects run:
shouldUnregister effect: _subjects.state.next({ values: control._getWatch() })
values effect: _reset(props.values, { keepFieldsRef: true })
setValue('name', 'test') is called (because _names.mount contains 'name')
_formValues['name'] = 'test'
_formValues = {} (resets the value!)
So after _reset, _formValues is {}, and the value 'test' is lost.
But then, when the user submits the form:
handleSubmit uses cloneObject(_formValues) = {}
- The form is submitted with empty values.
This is the bug!
The issue is that _reset resets _formValues to {} after calling setValue. And setValue only works for fields that are already registered. But the values are not persisted.
Actually, wait. Let me re-read the _reset function. After setValue is called for each field in _names.mount, _formValues is set to {}. But setValue already set the values.
Hmm, but _formValues = {} overwrites the entire object, including the values set by setValue.
So the fix should be to not reset _formValues to {} when keepFieldsRef is true.
But wait, this is by design. When shouldUnregister is true, the _formValues is intentionally reset to {} after the reset. The values are only in _defaultValues, and they're re-populated when fields are registered.
The issue is that the values are set in _formValues BEFORE _reset is called (when fields are registered). And then _reset resets _formValues to {}, overwriting the values.
So the fix should be to ensure that when shouldUnregister is true and keepFieldsRef is true, the _formValues is not reset to {}. Instead, it should be set to {} but the values for registered fields should be restored.
Actually, I think I understand the issue now. Let me re-read the values effect:
React.useEffect(() => {
if (props.values && !deepEqual(props.values, _values.current)) {
control._reset(props.values, {
keepFieldsRef: true,
...control._options.resetOptions,
});
// ...
}
}, [control, props.values]);
This effect calls _reset(props.values, { keepFieldsRef: true }). The keepFieldsRef option is supposed to keep the values for registered fields. But the implementation doesn't work correctly with shouldUnregister.
Looking at the _reset function:
setValue is called for each field in _names.mount
_formValues is set to {} (because shouldUnregister is true)
So setValue sets the values, but then _formValues is reset to {}, overwriting them.
The fix should be to not reset _formValues to {} when keepFieldsRef is true and fields have values.
Actually wait, let me re-check. When setValue is called, it sets the value in _formValues:
if (!isValueUnchanged) {
set(_formValues, name, cloneValue);
}
So after setValue('name', 'test'), _formValues['name'] = 'test'. Then _formValues = {} overwrites this.
But the next time the user interacts with the form, setValue would be called again (when the user types in the input). So the value would be re-set.
But the issue is that the user might submit the form immediately (without interacting). In that case, the values are lost.
OK so I think I finally understand the issue. Let me summarize:
- User passes
values: { name: 'test' } and shouldUnregister: true to useForm.
- Component renders, inputs are registered, and their values are set in
_formValues.
- Effects run,
_reset is called, which:
a. Calls setValue for each registered field (setting _formValues['name'] = 'test')
b. Resets _formValues to {} (because shouldUnregister is true)
- User submits the form.
handleSubmit uses cloneObject(_formValues) = {}.
- The form is submitted with empty values.
The fix should be to not reset _formValues to {} after setValue is called for registered fields.
Looking at the code:
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
The issue is that _formValues is always reset after setValue is called. The fix should be to preserve the values for registered fields.
One approach is to set _formValues to {} only if there are no registered fields. If there are registered fields, _formValues should have the values for those fields.
Actually, I think the issue is more subtle. Let me re-read the _reset function.
When shouldUnregister is true and the user doesn't pass keepDefaultValues, _formValues is set to {}. This is intentional, because the values are not stored in _formValues - they're stored in _defaultValues.
But when keepFieldsRef is true, the values are supposed to be preserved for registered fields. So _formValues should be set to {} initially, but then setValue should set the values.
Wait, but setValue sets the values BEFORE _formValues is reset to {}. So the values are lost.
Actually, let me re-check the order of operations:
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
The order is:
setValue is called for each field in _names.mount
_formValues is set to {} (or _defaultValues if keepDefaultValues is passed)
So setValue sets the values, but then _formValues is reset to {}, overwriting them.
The fix should be to NOT reset _formValues to {} when keepFieldsRef is true and there are registered fields.
Actually, I think the fix is simpler. When keepFieldsRef is true, the values for registered fields are set by setValue. And after _formValues is reset, those values are lost. So the fix should be to reset _formValues BEFORE calling setValue, or to set _formValues to {} only if there are no registered fields.
Wait, actually, I think the issue is that setValue sets the value in _formValues, but then _formValues is reset. So the values are lost.
The fix should be to NOT reset _formValues to {} when keepFieldsRef is true. Instead, _formValues should be set to {}, and then setValue should restore the values.
But the current order is:
setValue sets the values
_formValues is reset to {}
So the fix should be to swap the order:
_formValues is reset to {}
setValue sets the values
Wait, but that doesn't make sense. If _formValues is reset to {} first, then setValue would set the values from scratch. Which is fine.
Actually, I think the issue is that the current order is wrong. Let me re-check:
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
The order is:
setValue is called (sets values in _formValues)
_formValues is reset to {}
So the values set by setValue are lost.
The fix should be to swap the order:
_formValues is reset to {}
setValue is called (sets values in the new _formValues)
But wait, that would mean setValue is called AFTER _formValues is reset. And setValue sets the values in _formValues. So the values would be preserved.
Let me think about this more carefully. The issue is that _formValues = {} overwrites the values set by setValue. So the fix should be to set _formValues to {} BEFORE calling setValue.
But actually, I'm not sure this is the right fix. Let me re-read the _reset function.
Actually, wait. I think I misread the code. Let me re-check the order of operations:
Looking at the code:
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
The order is:
setValue is called for each field in _names.mount
_formValues is reset to {} (or _defaultValues if keepDefaultValues is passed)
_subjects.array.next and _subjects.state.next are called
So the values set by setValue are lost when _formValues is reset.
The fix should be to swap the order:
_formValues is reset to {} (or _defaultValues if keepDefaultValues is passed)
setValue is called for each field in _names.mount
This way, setValue sets the values in the new _formValues, and they're preserved.
Let me verify this fix by tracing through the flow:
-
createFormControl(props) is called:
_defaultValues = cloneObject(props.values) = { name: 'test' }
_formValues = {} (because shouldUnregister is true)
-
Component renders:
- Input with
register('name') is created
register('name') is called
updateValidAndValue('name', true, undefined) is called
_formValues['name'] = _defaultValues['name'] = 'test'
-
Effects run:
shouldUnregister effect: _subjects.state.next({ values: control._getWatch() })
values effect: _reset(props.values, { keepFieldsRef: true })
_defaultValues = cloneObject(props.values) = { name: 'test' }
_formValues is reset to {} (because shouldUnregister is true)
setValue('name', 'test') is called (because _names.mount contains 'name')
_formValues['name'] = 'test'
_subjects.state.next({ values: { name: 'test' } }) is called
-
User submits the form.
-
handleSubmit uses cloneObject(_formValues) = { name: 'test' }.
-
The form is submitted with the correct values.
Yes, this should work!
But wait, I need to make sure that swapping the order doesn't break other things. Let me think about the implications:
If _formValues is reset BEFORE setValue is called, then setValue would set the values in the new _formValues. This should be fine.
But what if there are unmounted fields? The _names.mount set only contains mounted fields. So setValue would only be called for mounted fields. Unmounted fields would not have their values set in _formValues.
This is the expected behavior, because when shouldUnregister is true, unmounted fields should not have their values stored.
OK so I think the fix is to swap the order of operations in _reset. Let me implement this fix.
Actually wait, let me also check if there are any edge cases. What if keepDefaultValues is passed?
If keepDefaultValues is passed, _formValues is set to _defaultValues:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
So if keepDefaultValues is true, _formValues is set to _defaultValues, which has the default values. And setValue would overwrite the values for registered fields.
But if keepDefaultValues is false, _formValues is set to {}. And setValue would set the values.
This is the expected behavior.
OK let me implement the fix.
Actually, wait. I want to double-check my understanding of the issue. Let me look at the test case again:
it('should load initial form values which are loaded async', async () => {
// ...
const App = ({ values }: { values: FormValues }) => {
const { register } = useForm({
values,
});
return (
<form>
<input {...register('test')} />
</form>
);
};
// ...
});
This test doesn't use shouldUnregister. So it's a different issue.
Let me search for tests that use both values and shouldUnregister:
Actually, I didn't find any tests that use both values and shouldUnregister. So this might be a new bug that wasn't covered by tests.
OK let me implement the fix. The fix is to swap the order of operations in _reset:
_formValues is reset BEFORE calling setValue
setValue sets the values in the new _formValues
Let me also think about other edge cases:
- What if
keepDirtyValues is passed?
- What if
keepFieldsRef is not passed?
- What if there are no registered fields?
Let me re-read the _reset function:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
if (isWeb && isUndefined(formValues)) {
// ...
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The _formValues reset is outside the if (keepStateOptions.keepFieldsRef) block. So _formValues is always reset, regardless of whether keepFieldsRef is passed.
The fix should be to swap the order of the if (keepStateOptions.keepFieldsRef) block and the _formValues reset.
Let me implement this fix.
Actually, I want to think about this more carefully. The issue is:
- When
shouldUnregister is true, _formValues is set to {} after _reset.
- When fields are registered (before
_reset), their values are set in _formValues.
- When
_reset is called, setValue sets the values for registered fields.
- Then
_formValues is set to {}, overwriting the values set by setValue.
The fix should be to NOT overwrite the values set by setValue. This can be done by:
- Resetting
_formValues BEFORE calling setValue, OR
- Not resetting
_formValues if keepFieldsRef is passed and there are registered fields.
Option 1 is simpler and cleaner. Let me implement it.
The fix is to swap the order:
if (!keepStateOptions.keepValues) {
// ...
// Reset _formValues first
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
// Then call setValue for registered fields
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
}
}
Wait, but I need to make sure this doesn't break the keepDirtyValues branch. Let me re-check:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
// ...
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The _formValues reset is outside the if (keepStateOptions.keepFieldsRef) block. So it always runs.
The fix should be to move the _formValues reset inside the else branch, before the if (keepStateOptions.keepFieldsRef) block.
Actually, wait. The _formValues reset is needed for all cases. It's not just for the keepFieldsRef case. So I can't just move it inside the else branch.
Hmm, let me think about this differently. The issue is that the order of operations is wrong. _formValues is reset AFTER setValue is called. The fix should be to reset _formValues BEFORE setValue is called.
But the _formValues reset is needed for all cases (not just keepFieldsRef). So I can't just move it inside the keepFieldsRef block.
One approach is to create a separate block for the _formValues reset that runs first, and then call setValue inside the keepFieldsRef block.
Let me implement this:
if (!keepStateOptions.keepValues) {
// Reset _formValues first
const newFormValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
if (isWeb && isUndefined(formValues)) {
// ...
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = newFormValues;
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this still has the same problem. _formValues is set AFTER setValue is called.
The fix should be to set _formValues BEFORE setValue is called. But then setValue would set the values in the new _formValues.
Hmm, but setValue doesn't directly set _formValues. It calls _setValue, which does:
if (!isValueUnchanged) {
set(_formValues, name, cloneValue);
}
So setValue sets _formValues[name] = cloneValue. If _formValues is already set to {}, then setValue would add the values.
So the fix should be to set _formValues to {} BEFORE calling setValue, and then setValue would add the values.
But the issue is that _formValues is set AFTER setValue is called. So setValue sets the values, and then _formValues is reset to {}, overwriting them.
The fix is to swap the order:
- Set
_formValues to {} (or _defaultValues)
- Call
setValue to add values for registered fields
But the _formValues reset is currently outside the keepFieldsRef block. So I need to be careful not to break the other cases.
Actually, I think the issue is that the _formValues reset is currently AFTER the keepFieldsRef block. The fix should be to move it BEFORE the keepFieldsRef block.
But the _formValues reset is needed for all cases. So I can't just move it inside the keepFieldsRef block.
Let me think about this differently. The issue is:
- When
shouldUnregister is true, _formValues is set to {} after _reset.
- When fields are registered (before
_reset), their values are set in _formValues.
- When
_reset is called, setValue sets the values for registered fields.
- Then
_formValues is set to {}, overwriting the values set by setValue.
The fix should be to ensure that _formValues is set BEFORE setValue is called. This way, setValue would set the values in the new _formValues.
But the _formValues reset is currently AFTER the keepFieldsRef block. So I need to move it BEFORE the keepFieldsRef block.
One approach is to extract the _formValues reset into a separate variable, set _formValues early, and then update _formValues again if needed.
Actually, let me just swap the order of the _formValues reset and the keepFieldsRef block:
if (!keepStateOptions.keepValues) {
// Reset _formValues first
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
if (isWeb && isUndefined(formValues)) {
// ...
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this would mean _formValues is set BEFORE the keepDirtyValues block. And the keepDirtyValues block might modify _formValues.
Let me re-read the keepDirtyValues block:
if (keepStateOptions.keepDirtyValues) {
const fieldsToCheck = new Set([
..._names.mount,
...Object.keys(getDirtyFields(_defaultValues, _formValues)),
]);
for (const fieldName of Array.from(fieldsToCheck)) {
const isDirty = get(_formState.dirtyFields, fieldName);
const existingValue = get(_formValues, fieldName);
const newValue = get(values, fieldName);
if (isDirty && !isUndefined(existingValue)) {
set(values, fieldName, existingValue);
} else if (!isDirty && !isUndefined(newValue)) {
setValue(fieldName as FieldPath<TFieldValues>, newValue);
}
}
}
The keepDirtyValues block modifies values (not _formValues), and then calls setValue for dirty fields. So the order doesn't matter much for this block.
But for the keepFieldsRef block, the order matters. setValue is called, and then _formValues is reset. The fix should be to reset _formValues BEFORE calling setValue.
So the fix is to swap the order of the _formValues reset and the keepFieldsRef block.
Actually, wait. The _formValues reset is currently:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
This line overwrites _formValues. So if I move this line before the keepFieldsRef block, setValue would set the values in the new _formValues.
Let me trace through the flow with this fix:
_formValues is set to {} (because shouldUnregister is true and keepDefaultValues is not passed)
setValue('name', 'test') is called
setValue sets _formValues['name'] = 'test'
- The form is submitted with
_formValues = { name: 'test' }.
Yes, this should work!
But I need to make sure that the _subjects.state.next({ values: { ...values } }) call still works correctly. The payload has values, which is cloneObject(props.values). So the subscribers receive the correct values.
OK I'm confident that the fix is to swap the order of the _formValues reset and the keepFieldsRef block. Let me implement it.
Actually, let me double-check by looking at the current code structure:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The fix is to move the _formValues reset BEFORE the if (keepStateOptions.keepFieldsRef) block:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this would mean the _formValues reset is inside the if (keepStateOptions.keepFieldsRef) block. And the _formValues reset is needed for all cases (not just keepFieldsRef).
Hmm, let me think about this more carefully. The _formValues reset is needed for all cases. So it should be outside the if (keepStateOptions.keepFieldsRef) block.
But the issue is that the _formValues reset overwrites the values set by setValue. So I need to ensure that _formValues is reset BEFORE setValue is called.
One approach is to move the _formValues reset to the top of the block, and then call setValue later:
if (!keepStateOptions.keepValues) {
// Reset _formValues first
const newFormValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = newFormValues;
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this still has the same problem. setValue is called BEFORE _formValues = newFormValues. So setValue sets the values in the old _formValues, and then _formValues is set to newFormValues, overwriting the values.
The fix should be to set _formValues to newFormValues BEFORE calling setValue:
if (!keepStateOptions.keepValues) {
// Reset _formValues first
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but the _formValues reset is currently inside the if (!keepStateOptions.keepValues) block. If I move it to the top of the block, it would be outside the if (keepStateOptions.keepFieldsRef) block. So it would run for all cases.
And then setValue is called inside the if (keepStateOptions.keepFieldsRef) block. So setValue would set the values in the new _formValues.
Yes, this should work!
Let me trace through the flow with this fix:
_formValues is set to {} (because shouldUnregister is true and keepDefaultValues is not passed)
setValue('name', 'test') is called
setValue sets _formValues['name'] = 'test'
_subjects.state.next({ values: { name: 'test' } }) is called
- The form is submitted with
_formValues = { name: 'test' }.
Yes, this should work!
But I need to make sure that the _subjects.state.next({ values: { ...values } }) call still works correctly. The payload has values, which is cloneObject(props.values). So the subscribers receive the correct values.
OK I'm confident that the fix is to move the _formValues reset to the top of the block. Let me implement it.
Actually, wait. I want to double-check that the fix doesn't break other cases. Let me think about what happens when shouldUnregister is false:
_formValues is set to cloneObject(values) = cloneObject(props.values) = { name: 'test' }
setValue('name', 'test') is called
setValue sets _formValues['name'] = 'test' (but it's already 'test', so no change)
- The form is submitted with
_formValues = { name: 'test' }.
This should work correctly.
And what about when keepDefaultValues is true:
_formValues is set to cloneObject(_defaultValues) = { name: 'test' }
setValue('name', 'test') is called
setValue sets _formValues['name'] = 'test' (but it's already 'test', so no change)
- The form is submitted with
_formValues = { name: 'test' }.
This should also work correctly.
And what about when keepFieldsRef is false:
_formValues is set to {} (because shouldUnregister is true and keepDefaultValues is not passed)
_fields = {} (fields are cleared)
- The form is submitted with
_formValues = {}.
This is the expected behavior, because when keepFieldsRef is false, the values are not preserved.
OK I'm confident that the fix is correct. Let me implement it.
Wait, actually I realize I need to also think about the _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues); line more carefully.
This line sets _formValues based on:
shouldUnregister: If true, _formValues is {} (or _defaultValues if keepDefaultValues is passed)
shouldUnregister is false: _formValues is cloneObject(values)
So when shouldUnregister is true, _formValues is reset to {}. And setValue should set the values.
When shouldUnregister is false, _formValues is set to cloneObject(values), which already has the values. And setValue would overwrite them (but with the same values).
So the fix should work for both cases.
Actually, I realize there's still a potential issue. Let me re-check the _reset function:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The _formValues reset is:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
This line uses _options.shouldUnregister. And _options is updated on every render:
const control = _formControl.current.control;
control._options = props;
So _options.shouldUnregister is props.shouldUnregister. If the user passes shouldUnregister: true, then _options.shouldUnregister is true.
And the _formValues reset is:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
If _options.shouldUnregister is true and keepStateOptions.keepDefaultValues is false, then _formValues = {}.
OK so the fix is correct. Let me implement it.
Actually wait, I just realized something. The fix should be to set _formValues to {} BEFORE calling setValue. But the _formValues reset is currently:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
If I move this line before the keepFieldsRef block, then:
_formValues is set to {}
setValue('name', 'test') is called
setValue sets _formValues['name'] = 'test'
But then, what about the _formValues reset? It's set to {}, and then setValue sets the values. So the final _formValues has the values set by setValue.
But the current _formValues reset is at the end of the block. If I move it to the top of the block, then _formValues is reset, and then setValue is called. So the final _formValues has the values set by setValue.
Yes, this should work!
Let me also think about whether the fix breaks the keepDirtyValues case:
_formValues is set to {} (because shouldUnregister is true and keepDefaultValues is not passed)
keepDirtyValues block runs:
const fieldsToCheck = new Set([
..._names.mount,
...Object.keys(getDirtyFields(_defaultValues, _formValues)),
]);
for (const fieldName of Array.from(fieldsToCheck)) {
const isDirty = get(_formState.dirtyFields, fieldName);
const existingValue = get(_formValues, fieldName);
const newValue = get(values, fieldName);
if (isDirty && !isUndefined(existingValue)) {
set(values, fieldName, existingValue);
} else if (!isDirty && !isUndefined(newValue)) {
setValue(fieldName as FieldPath<TFieldValues>, newValue);
}
}
_formValues is {}, so getDirtyFields(_defaultValues, _formValues) would return the dirty fields.
- For each dirty field,
existingValue is get(_formValues, fieldName), which is undefined (because _formValues is {}).
- So the condition
isDirty && !isUndefined(existingValue) is false.
- For each non-dirty field,
setValue is called.
Hmm, this might not work correctly. Let me think about it more carefully.
Actually, the keepDirtyValues block modifies values (not _formValues), and then calls setValue. So the order of _formValues reset doesn't matter for the keepDirtyValues case.
Wait, but getDirtyFields(_defaultValues, _formValues) uses _formValues. If _formValues is {}, then getDirtyFields might return wrong results.
Let me re-read the getDirtyFields function:
Actually, I don't have the getDirtyFields function in front of me. Let me assume it returns the fields where the values differ between _defaultValues and _formValues.
If _formValues is {} and _defaultValues is { name: 'test' }, then getDirtyFields(_defaultValues, _formValues) would return { name: true } (because the values differ).
And in the keepDirtyValues block:
if (isDirty && !isUndefined(existingValue)) {
set(values, fieldName, existingValue);
} else if (!isDirty && !isUndefined(newValue)) {
setValue(fieldName as FieldPath<TFieldValues>, newValue);
}
If isDirty is true and existingValue is undefined (because _formValues is {}), then the condition is false. So nothing happens for dirty fields.
And if isDirty is false and newValue is defined, then setValue is called.
Hmm, this might not be the correct behavior. But I think the keepDirtyValues case is separate from the keepFieldsRef case. So I shouldn't worry about it.
Let me focus on the keepFieldsRef case. The fix is to set _formValues to {} BEFORE calling setValue. And this should work correctly for the keepFieldsRef case.
Actually, I realize I might be overcomplicating this. Let me just look at the current code and understand what it does:
Current code:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
if (isWeb && isUndefined(formValues)) {
// ...
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The issue is that _formValues is reset AFTER setValue is called. So the values set by setValue are overwritten.
The fix is to reset _formValues BEFORE setValue is called. So I need to move the _formValues reset line before the if (keepStateOptions.keepFieldsRef) block.
But the _formValues reset line is currently inside the if (!keepStateOptions.keepValues) block. So I can move it to the top of this block.
Let me implement this fix:
if (!keepStateOptions.keepValues) {
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepDirtyValues) {
// ...
} else {
if (isWeb && isUndefined(formValues)) {
// ...
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this would mean _formValues is reset BEFORE the keepDirtyValues block. And the keepDirtyValues block uses _formValues to get dirty fields.
Let me re-read the keepDirtyValues block:
if (keepStateOptions.keepDirtyValues) {
const fieldsToCheck = new Set([
..._names.mount,
...Object.keys(getDirtyFields(_defaultValues, _formValues)),
]);
for (const fieldName of Array.from(fieldsToCheck)) {
const isDirty = get(_formState.dirtyFields, fieldName);
const existingValue = get(_formValues, fieldName);
const newValue = get(values, fieldName);
if (isDirty && !isUndefined(existingValue)) {
set(values, fieldName, existingValue);
} else if (!isDirty && !isUndefined(newValue)) {
setValue(fieldName as FieldPath<TFieldValues>, newValue);
}
}
}
The keepDirtyValues block uses _formValues to get dirty fields. If _formValues is reset to {}, then getDirtyFields(_defaultValues, _formValues) might return different results.
Hmm, this could break the keepDirtyValues case. Let me think about it more carefully.
Actually, I think the keepDirtyValues case is separate from the keepFieldsRef case. The issue is with keepFieldsRef, not keepDirtyValues.
So I should only move the _formValues reset for the keepFieldsRef case. For the keepDirtyValues case, I should keep the _formValues reset at the end.
Let me re-think the fix:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block - _formValues reset stays at the end
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
// Reset _formValues first for keepFieldsRef case
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, but this means the _formValues reset is inside the else block (not the keepDirtyValues block). So it only runs for the non-keepDirtyValues case.
And then _formValues is set to {} (or _defaultValues if keepDefaultValues is passed) BEFORE setValue is called. So setValue would set the values in the new _formValues.
Yes, this should work!
But wait, what about the _formValues reset line? In the current code, it's:
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
I'm moving this line from the end of the if (!keepStateOptions.keepValues) block to the beginning of the else block. But I need to make sure that the _formValues reset is not duplicated.
Let me re-check the current code structure:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
The _formValues reset is inside the if (!keepStateOptions.keepValues) block, but outside both the if (keepStateOptions.keepDirtyValues) and if (keepStateOptions.keepFieldsRef) blocks.
So the _formValues reset runs for all cases (except when keepValues is passed).
If I move the _formValues reset to the beginning of the else block (inside if (!keepStateOptions.keepValues) but outside if (keepStateOptions.keepDirtyValues)), it would run for all cases except keepDirtyValues.
But I also need to make sure that the _formValues reset still runs for the keepDirtyValues case. In the current code, it runs for all cases. If I move it inside the else block, it wouldn't run for the keepDirtyValues case.
Hmm, this is getting complicated. Let me think about it differently.
Actually, I think the issue is specifically with the keepFieldsRef case. And the keepDirtyValues case is separate. So I should only fix the keepFieldsRef case.
The fix for the keepFieldsRef case is to move the _formValues reset line BEFORE the if (keepStateOptions.keepFieldsRef) block. But the _formValues reset line is currently outside both the if (keepStateOptions.keepDirtyValues) and if (keepStateOptions.keepFieldsRef) blocks.
So I can't just move the _formValues reset line to a specific location. I need to be more careful.
One approach is to extract the _formValues reset logic into a separate variable, and then set _formValues early. For the keepDirtyValues case, I don't change _formValues early. For the non-keepDirtyValues case, I set _formValues early.
Let me implement this:
if (!keepStateOptions.keepValues) {
if (keepStateOptions.keepDirtyValues) {
// keepDirtyValues block
} else {
if (isWeb && isUndefined(formValues)) {
// browser reset block
}
// Reset _formValues first for keepFieldsRef case
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
if (keepStateOptions.keepFieldsRef) {
for (const fieldName of _names.mount) {
setValue(
fieldName as FieldPath<TFieldValues>,
get(values, fieldName),
);
}
} else {
_fields = {};
}
}
// Only set _formValues here if we didn't set it earlier (keepDirtyValues case)
if (keepStateOptions.keepDirtyValues) {
_formValues = _options.shouldUnregister
? keepStateOptions.keepDefaultValues
? (cloneObject(_defaultValues) as TFieldValues)
: ({} as TFieldValues)
: (cloneObject(values) as TFieldValues);
}
_subjects.array.next({
values: { ...values },
});
_subjects.state.next({
values: { ...values } as TFieldValues,
});
}
Wait, this is getting too complicated. Let me think about it more carefully.
Actually, I think the simplest fix is to just move the _formValues reset line to the top of the if (!keepStateOptions.keepValues) block, and then remove it from the bottom.
This way, _formValues is reset at the beginning, and setValue sets the values in the new _formValues.
But the keepDirtyValues block uses _formValues to get dirty fields. If _formValues is reset to {}, then getDirtyFields(_defaultValues, _formValues) might return wrong results.
Let me check what getDirtyFields does:
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -n "getDirtyFields" /react-hook-form/src/logic/getDirtyFields.ts | head -20
</tool_call>