Skip to content

Commit

Permalink
👍 close #12108 useController should subscribe to exact field name of …
Browse files Browse the repository at this point in the history
…form's state (#12109)
  • Loading branch information
Wendystraite authored Jul 23, 2024
1 parent c01e64a commit 961b4d0
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 1 deletion.
94 changes: 93 additions & 1 deletion src/__tests__/useController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ describe('useController', () => {

fireEvent.blur(screen.getAllByRole('textbox')[0]);

expect(renderCounter).toEqual([2, 5]);
expect(renderCounter).toEqual([2, 3]);
});

describe('checkbox', () => {
Expand Down Expand Up @@ -1012,4 +1012,96 @@ describe('useController', () => {
}),
);
});

it('should subscribe to exact form state update', () => {
type FormValues = {
test: string;
test_with_suffix: string;
};

const renderCounter: Record<keyof FormValues, number> = {
test: 0,
test_with_suffix: 0,
};

const ControlledInput = ({
name,
control,
}: {
name: keyof FormValues;
control: Control<FormValues>;
}) => {
const {
field,
fieldState: { error, isDirty },
} = useController({
name,
control,
rules: { required: 'is required' },
});

renderCounter[name]++;

return (
<div>
<input aria-label={name} {...field} />
{error && (
<p>
{name} {error.message}
</p>
)}
{isDirty && <p>{name} isDirty</p>}
</div>
);
};

const App = () => {
const { control } = useForm<FormValues>({
mode: 'onBlur',
defaultValues: {
test: '1234',
test_with_suffix: '1234',
},
});
return (
<form>
<ControlledInput name="test" control={control} />
<ControlledInput name="test_with_suffix" control={control} />
</form>
);
};

render(<App />);

expect(renderCounter).toEqual({ test: 1, test_with_suffix: 1 });
expect(screen.queryByText('test is required')).toBeNull();
expect(screen.queryByText('test_with_suffix is required')).toBeNull();

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

fireEvent.blur(screen.getByRole('textbox', { name: 'test' }));

expect(screen.getByText('test isDirty')).toBeVisible();

expect(renderCounter).toEqual({ test: 2, test_with_suffix: 1 });

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

fireEvent.blur(screen.getByRole('textbox', { name: 'test_with_suffix' }));

expect(screen.getByText('test_with_suffix isDirty')).toBeVisible();

expect(renderCounter).toEqual({ test: 2, test_with_suffix: 2 });
});
});
1 change: 1 addition & 0 deletions src/useController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export function useController<
const formState = useFormState({
control,
name,
exact: true,
});

const _registerProps = React.useRef(
Expand Down

0 comments on commit 961b4d0

Please sign in to comment.