Skip to content

Commit 7a00e29

Browse files
committed
feat: make root lens to be watchable when name is an empty string (#27)
1 parent fc6c0a4 commit 7a00e29

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/LensCore.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ export class LensCore<T extends FieldValues> {
140140

141141
this.interopCache ??= {
142142
control: this.control,
143-
name: this.path,
143+
name: this.path || undefined,
144144
...(this.override ? { getTransformer: this.getTransformer.bind(this), setTransformer: this.setTransformer.bind(this) } : {}),
145145
};
146146

tests/lens.test.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useForm } from 'react-hook-form';
1+
import { useForm, useWatch } from 'react-hook-form';
22
import { type Lens, useLens } from '@hookform/lenses';
33
import { renderHook } from '@testing-library/react';
44
import { expectTypeOf } from 'vitest';
@@ -11,7 +11,7 @@ test('lens can be created', () => {
1111
});
1212

1313
expectTypeOf(result.current.lens).toEqualTypeOf<Lens<{ a: string }>>();
14-
expect(result.current.lens.interop()).toEqual({ name: '', control: result.current.form.control });
14+
expect(result.current.lens.interop()).toEqual({ name: undefined, control: result.current.form.control });
1515
});
1616

1717
test('lenses are different when created with different forms', () => {
@@ -27,3 +27,25 @@ test('lenses are different when created with different forms', () => {
2727
expect(result.current.form.control).toBe(result.current.lens1.interop().control);
2828
expect(result.current.form.control).toBe(result.current.lens2.interop().control);
2929
});
30+
31+
test('root lens should be watchable when name is an empty string in LensCore', () => {
32+
const { result } = renderHook(() => {
33+
const form = useForm({
34+
defaultValues: {
35+
a: 3,
36+
b: 'hello',
37+
},
38+
});
39+
40+
const lens = useLens({ control: form.control });
41+
const interop = lens.interop();
42+
const value = useWatch(interop);
43+
44+
return { form, interop, value };
45+
});
46+
47+
expect(result.current.interop).toEqual({ name: undefined, control: result.current.form.control });
48+
expect(result.current.value).toEqual({ a: 3, b: 'hello' });
49+
expect(result.current.value.a).toEqual(3);
50+
expect(result.current.value.b).toEqual('hello');
51+
});

0 commit comments

Comments
 (0)