Skip to content

Commit

Permalink
🐞 fix react-hook-form#11328 resetField with object as defaultValue (r…
Browse files Browse the repository at this point in the history
  • Loading branch information
geeee authored and rafaelcalhau committed May 5, 2024
1 parent bd1a036 commit 0f66ca0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
56 changes: 56 additions & 0 deletions src/__tests__/useForm/resetField.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -408,5 +408,61 @@ describe('resetField', () => {
expect(await screen.findByText('NotValid')).toBeVisible();
expect(screen.getByText('error')).toBeVisible();
});

it('should work with objects as defaultValue', async () => {
const App = () => {
const {
register,
resetField,
formState: { isDirty },
} = useForm({
defaultValues: {
nestedObjectTest: {
test: 'test',
},
},
mode: 'onChange',
});

return (
<form>
<input {...register('nestedObjectTest.test', { maxLength: 4 })} />
<p>{isDirty ? 'isDirty' : 'isNotDirty'}</p>
<button
type={'button'}
onClick={() => {
resetField('nestedObjectTest', {
defaultValue: { test: 'test2' },
});
}}
>
reset
</button>
</form>
);
};

render(<App />);

expect(await screen.findByText('isNotDirty')).toBeVisible();

fireEvent.change(screen.getByRole('textbox'), {
target: {
value: 'abcd',
},
});

expect(await screen.findByText('isDirty')).toBeVisible();

fireEvent.click(screen.getByRole('button'));

fireEvent.change(screen.getByRole('textbox'), {
target: {
value: '1234',
},
});

expect(await screen.findByText('isDirty')).toBeVisible();
});
});
});
6 changes: 3 additions & 3 deletions src/logic/createFormControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1149,7 +1149,7 @@ export function createFormControl<
const resetField: UseFormResetField<TFieldValues> = (name, options = {}) => {
if (get(_fields, name)) {
if (isUndefined(options.defaultValue)) {
setValue(name, get(_defaultValues, name));
setValue(name, cloneObject(get(_defaultValues, name)));
} else {
setValue(
name,
Expand All @@ -1158,7 +1158,7 @@ export function createFormControl<
FieldPath<TFieldValues>
>,
);
set(_defaultValues, name, options.defaultValue);
set(_defaultValues, name, cloneObject(options.defaultValue));
}

if (!options.keepTouched) {
Expand All @@ -1168,7 +1168,7 @@ export function createFormControl<
if (!options.keepDirty) {
unset(_formState.dirtyFields, name);
_formState.isDirty = options.defaultValue
? _getDirty(name, get(_defaultValues, name))
? _getDirty(name, cloneObject(get(_defaultValues, name)))
: _getDirty();
}

Expand Down

0 comments on commit 0f66ca0

Please sign in to comment.