Skip to content

Commit

Permalink
馃悶 fix #5678 reset with keep default values with Controller (#5688)
Browse files Browse the repository at this point in the history
* fix #5678 reset with keey default values with Controller

* follow up with unit test coverage
  • Loading branch information
bluebill1049 committed Jun 19, 2021
1 parent 4c3fdab commit 516da67
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
53 changes: 52 additions & 1 deletion src/__tests__/useForm/reset.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
import { act, renderHook } from '@testing-library/react-hooks';

import { Controller } from '../../controller';
import { NestedValue, UseFormReturn } from '../../types';
import { Control, NestedValue, UseFormReturn } from '../../types';
import { useController } from '../../useController';
import { useFieldArray } from '../../useFieldArray';
import { useForm } from '../../useForm';

Expand Down Expand Up @@ -464,4 +465,54 @@ describe('reset', () => {

expect(getValuesResult).toMatchSnapshot();
});

it('should keep defaultValues after reset with shouldKeepDefaultValues', async () => {
type FormValues = { test: string; test1: string };
const ControlledInput = ({ control }: { control: Control<FormValues> }) => {
const { field } = useController({
name: 'test',
control,
});

return <input {...field} />;
};

function App() {
const { control, register, reset } = useForm<FormValues>({
defaultValues: { test: 'test', test1: 'test1' },
});
const resetData = () => {
reset({}, { keepDefaultValues: true });
};

return (
<form>
<ControlledInput control={control} />
<input {...register('test1')} />
<input type="button" onClick={resetData} value="Reset" />
</form>
);
}

render(<App />);

fireEvent.change(screen.getAllByRole('textbox')[0], {
target: { value: 'data' },
});

fireEvent.change(screen.getAllByRole('textbox')[1], {
target: { value: 'data' },
});

await actComponent(async () => {
fireEvent.click(screen.getByRole('button'));
});

expect(
(screen.getAllByRole('textbox')[0] as HTMLInputElement).value,
).toEqual('test');
expect(
(screen.getAllByRole('textbox')[1] as HTMLInputElement).value,
).toEqual('test1');
});
});
4 changes: 3 additions & 1 deletion src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,9 @@ export function useForm<
fieldsRef.current = {};

subjectsRef.current.control.next({
values: { ...updatedValues },
values: keepStateOptions.keepDefaultValues
? defaultValuesRef.current
: { ...updatedValues },
});

subjectsRef.current.watch.next({
Expand Down

0 comments on commit 516da67

Please sign in to comment.