Skip to content

Commit da420f1

Browse files
committed
feat(forms): include isRegistered flag on useFormControl2
1 parent ce5ea8e commit da420f1

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

demo/Form2Examples.jsx

+7-7
Original file line numberDiff line numberDiff line change
@@ -85,15 +85,15 @@ function FormVersion() {
8585
}
8686

8787
function FormArray() {
88-
const { getValue, setValue } = useFormControl2('arr');
88+
const { getValue, setValue, isRegistered } = useFormControl2('arr');
8989

9090
useEffect(() => {
91-
setValue((prev) => {
92-
console.log('useEffect.setValue [arr] :>> ', prev, getValue());
93-
94-
return prev;
95-
});
96-
}, [getValue, setValue]);
91+
if (isRegistered()) {
92+
console.log('initialized value [arr] :>> ', getValue());
93+
} else {
94+
console.log('uninitialized value [arr] :>> ', getValue());
95+
}
96+
}, [getValue, setValue, isRegistered]);
9797

9898
return (getValue() || []).map((v, index) => <FormInput2 key={index} name={`arr[${index}]`} />);
9999
}

src/forms2/helpers/useFormControl.jsx

+5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { FormContext } from './useFormHelper';
66
export function useFormControl2(name, type) {
77
const formHelper = useContext(FormContext);
88
const [value, _setValue] = useState('');
9+
const [isRegistered, setIsRegistered] = useState(false);
910

1011
const setValue = useCallback(
1112
(newValue) => {
@@ -39,6 +40,7 @@ export function useFormControl2(name, type) {
3940
formHelper.register(name, {
4041
setValue: _setValue,
4142
});
43+
setIsRegistered(true);
4244
// eslint-disable-next-line react-hooks/exhaustive-deps
4345
}, []);
4446

@@ -47,6 +49,9 @@ export function useFormControl2(name, type) {
4749
return value;
4850
},
4951
setValue,
52+
isRegistered() {
53+
return isRegistered;
54+
},
5055
handleOnChangeFactory: (afterChange, type) => (e) => {
5156
const newValue = handleOnChange(e, type);
5257

0 commit comments

Comments
 (0)