Skip to content

Commit e94f961

Browse files
committed
feat(forms2): useFormEffect allows a "name" argument for watching data changes
1 parent ef21501 commit e94f961

File tree

3 files changed

+18
-9
lines changed

3 files changed

+18
-9
lines changed

demo/Form2Examples.jsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,8 @@ function FormArrayOfObjects() {
115115
function FormObserver() {
116116
const [state, setState] = useState(0);
117117

118-
useFormEffect((formData) => {
119-
console.log('FormObserver.formData :>> ', formData);
118+
useFormEffect('Obj', (data) => {
119+
console.log('FormObserver :>> ', data);
120120
setState((p) => p + 1);
121121
});
122122

src/forms2/helpers/useFormEffect.jsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { useContext, useEffect } from 'react';
22
import { FormContext } from './useFormHelper';
33

4-
export function useFormEffect(observerFn) {
4+
export function useFormEffect(name, observerFn) {
55
const formHelper = useContext(FormContext);
66

77
useEffect(() => {
8-
const unsubscribe = formHelper.subscribe(observerFn);
8+
const unsubscribe = formHelper.subscribe(name, observerFn);
99

1010
return () => unsubscribe();
1111
// eslint-disable-next-line react-hooks/exhaustive-deps

src/forms2/helpers/useFormHelper.jsx

+14-5
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ export class FormHelper {
3434
}
3535

3636
notifyListeners(formData) {
37-
for (const listener of this.listeners) {
37+
for (const { name, observerFn } of this.listeners) {
3838
setTimeout(() => {
39-
listener.observerFn(formData);
39+
observerFn(getValueByPath(formData, name));
4040
}, 0);
4141
}
4242
}
@@ -59,13 +59,22 @@ export class FormHelper {
5959
this.listeners = this.listeners.filter(({ id }) => id !== listenerId);
6060
}
6161

62-
subscribe(observerFn) {
62+
subscribe(_name, _observerFn) {
6363
const listenerId = this.nextListenerId;
6464

65+
let name = _name,
66+
observerFn = _observerFn;
67+
68+
if (!_observerFn) {
69+
observerFn = name;
70+
name = '';
71+
}
72+
6573
this.nextListenerId += 1;
6674

6775
this.listeners.push({
6876
id: listenerId,
77+
name,
6978
observerFn,
7079
});
7180

@@ -99,8 +108,8 @@ export function useFormHelper(initialValues, { debounceWait, transform, onChange
99108
register(name, formControl) {
100109
formHelper.current.register(name, formControl);
101110
},
102-
subscribe(observerFn) {
103-
return formHelper.current.subscribe(observerFn);
111+
subscribe(name, observerFn) {
112+
return formHelper.current.subscribe(name, observerFn);
104113
},
105114
};
106115
}

0 commit comments

Comments
 (0)