From 0f66ca088eccec3450309dcd42fc7e0257932d24 Mon Sep 17 00:00:00 2001 From: Ge Date: Fri, 22 Dec 2023 00:28:41 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9E=20fix=20#11328=20resetField=20with?= =?UTF-8?q?=20object=20as=20defaultValue=20(#11329)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/useForm/resetField.test.tsx | 56 +++++++++++++++++++++++ src/logic/createFormControl.ts | 6 +-- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/__tests__/useForm/resetField.test.tsx b/src/__tests__/useForm/resetField.test.tsx index d8fb98c52cc..66cf5ec651d 100644 --- a/src/__tests__/useForm/resetField.test.tsx +++ b/src/__tests__/useForm/resetField.test.tsx @@ -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 ( +
+ +

{isDirty ? 'isDirty' : 'isNotDirty'}

+ +
+ ); + }; + + render(); + + 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(); + }); }); }); diff --git a/src/logic/createFormControl.ts b/src/logic/createFormControl.ts index 56ad28e7960..dec1f411484 100644 --- a/src/logic/createFormControl.ts +++ b/src/logic/createFormControl.ts @@ -1149,7 +1149,7 @@ export function createFormControl< const resetField: UseFormResetField = (name, options = {}) => { if (get(_fields, name)) { if (isUndefined(options.defaultValue)) { - setValue(name, get(_defaultValues, name)); + setValue(name, cloneObject(get(_defaultValues, name))); } else { setValue( name, @@ -1158,7 +1158,7 @@ export function createFormControl< FieldPath >, ); - set(_defaultValues, name, options.defaultValue); + set(_defaultValues, name, cloneObject(options.defaultValue)); } if (!options.keepTouched) { @@ -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(); }