Skip to content

Commit f3ad852

Browse files
newsiberianoskarski
authored andcommitted
πŸš€ fix: skip call executeBuiltInValidation if no sub-fields left (react-hook-form#12054)
* fix: don't call `executeBuiltInValidation` if no sub-fields left * refactor: use `isEmptyObject` * chore: add tests to check the correct number of times `executeBuiltInValidation` called
1 parent 52bfc04 commit f3ad852

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { createFormControl } from '../../logic/createFormControl';
2+
import isEmptyObject from '../../utils/isEmptyObject';
3+
4+
jest.mock('../../utils/isEmptyObject', () => {
5+
const original = jest.requireActual('../../utils/isEmptyObject');
6+
return {
7+
__esModule: true,
8+
default: jest.fn(original.default),
9+
};
10+
});
11+
12+
describe('createFormControl', () => {
13+
it('should call `executeBuiltInValidation` once for a single field', async () => {
14+
const { register, control } = createFormControl({
15+
defaultValues: {
16+
foo: 'foo',
17+
},
18+
});
19+
20+
register('foo', {});
21+
22+
await control._updateValid(true);
23+
24+
expect(isEmptyObject).toHaveBeenCalledTimes(1);
25+
});
26+
27+
it('should call `executeBuiltInValidation` twice for a field as an object with a single sub-field', async () => {
28+
const { register, control } = createFormControl({
29+
defaultValues: {
30+
foo: {
31+
bar: 'bar',
32+
},
33+
},
34+
});
35+
36+
register('foo.bar', {});
37+
38+
await control._updateValid(true);
39+
40+
expect(isEmptyObject).toHaveBeenCalledTimes(2);
41+
});
42+
43+
it('should call executeBuiltInValidation the correct number of times in case the field is an array', async () => {
44+
const { register, control } = createFormControl({
45+
defaultValues: {
46+
foo: [
47+
{
48+
bar: 'bar',
49+
baz: 'baz',
50+
},
51+
{
52+
bar: 'bar',
53+
baz: 'baz',
54+
},
55+
],
56+
},
57+
});
58+
59+
register('foo.1.bar', {});
60+
61+
await control._updateValid(true);
62+
63+
expect(isEmptyObject).toHaveBeenCalledTimes(3);
64+
});
65+
});

β€Žsrc/logic/createFormControl.tsβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ export function createFormControl<
481481
: unset(_formState.errors, _f.name));
482482
}
483483

484-
fieldValue &&
484+
!isEmptyObject(fieldValue) &&
485485
(await executeBuiltInValidation(
486486
fieldValue,
487487
shouldOnlyCheckValid,

0 commit comments

Comments
Β (0)