Skip to content

Commit

Permalink
🐞 fixes #11386 get new dirtyFields when reset keeping defaults and di…
Browse files Browse the repository at this point in the history
…rty values (#11401)

* Add test

* Get newly-dirty fields when keeping defaults and dirty values
  • Loading branch information
IanVS authored Jan 16, 2024
1 parent f8bbb30 commit 4c21b28
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
76 changes: 76 additions & 0 deletions src/__tests__/useForm/reset.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,82 @@ describe('reset', () => {
}),
);
});

it('should treat previously-undirty fields as dirty when keepDefaultValues is set', async () => {
let updatedDirtyFields: Record<string, boolean> = {};
let updatedDirty = false;

function App() {
const {
reset,
register,
handleSubmit,
formState: { dirtyFields, isDirty },
} = useForm({ defaultValues: { firstName: '', lastName: '' } });

function resetKeepDefaults() {
reset(
{
firstName: 'bill',
lastName: 'luo',
},
{
keepDefaultValues: true,
keepDirtyValues: true,
},
);
}

updatedDirtyFields = dirtyFields;
updatedDirty = isDirty;

return (
<form
onSubmit={handleSubmit((data) => {
submittedValue = data;
})}
>
<input {...register('firstName')} placeholder="First Name" />
<input {...register('lastName')} placeholder="Last Name" />

<button
type="button"
onClick={() => {
resetKeepDefaults();
}}
>
reset keep defaults
</button>
<button>submit</button>
</form>
);
}

render(<App />);

fireEvent.click(
screen.getByRole('button', { name: 'reset keep defaults' }),
);

await waitFor(() =>
expect(
(screen.getByPlaceholderText('Last Name') as HTMLInputElement)
.value,
).toEqual('luo'),
);

expect(
(screen.getByPlaceholderText('First Name') as HTMLInputElement).value,
).toEqual('bill');

// Both fields were updated, the defaults were kept, so both should be dirty
expect(updatedDirtyFields).toEqual({
firstName: true,
lastName: true,
});

expect(updatedDirty).toBeTruthy();
});
});

describe('with controlled components', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/logic/createFormControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,9 @@ export function createFormControl<
? _formState.isSubmitted
: false,
dirtyFields: keepStateOptions.keepDirtyValues
? _formState.dirtyFields
? keepStateOptions.keepDefaultValues && _formValues
? getDirtyFields(_defaultValues, _formValues)
: _formState.dirtyFields
: keepStateOptions.keepDefaultValues && formValues
? getDirtyFields(_defaultValues, formValues)
: {},
Expand Down

0 comments on commit 4c21b28

Please sign in to comment.