Skip to content

Commit ce5ea8e

Browse files
committed
fix(forms2): allow update functions on useFormControl2 setValue
1 parent 2c06d8d commit ce5ea8e

File tree

2 files changed

+39
-20
lines changed

2 files changed

+39
-20
lines changed

demo/Form2Examples.jsx

+30-18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* eslint-disable no-console */
2-
import React from 'react';
2+
import React, { useEffect } from 'react';
33
import { Form2, FormInput2, FormSelect2, FormSwitch2, useFormControl2 } from '../dist/main';
44

55
export function Form2Examples() {
@@ -10,24 +10,28 @@ export function Form2Examples() {
1010
initialValues={{ attrA: 'ABC', Obj: { x: 'X' }, arr: [1, 2, 3], arrObj: [{ o: 1 }, { o: 2 }, { o: 3 }] }}
1111
onSubmit={console.info.bind(console, 'onSubmit')}
1212
onChange={console.info.bind(console, 'onChange')}
13-
transform={(formData) => ({
14-
__v: formData.__v ? formData.__v + 1 : 1,
15-
attrB: `${formData.attrB || ''}A`,
16-
Obj: {
17-
y: `${formData.Obj.y || ''}X`,
18-
w: {
19-
z: formData.__v ? formData.__v * 2 : 1,
13+
transform={(formData) => {
14+
console.log('transform', formData);
15+
16+
return {
17+
__v: formData.__v ? formData.__v + 1 : 1,
18+
attrB: `${formData.attrB || ''}A`,
19+
Obj: {
20+
y: `${formData.Obj.y || ''}X`,
21+
w: {
22+
z: formData.__v ? formData.__v * 2 : 1,
23+
},
24+
t: formData.__v % 2 ? null : undefined,
25+
u: new Date(),
2026
},
21-
t: formData.__v % 2 ? null : undefined,
22-
u: new Date(),
23-
},
24-
arr: formData.arr.map((v) => parseFloat(v) + 1),
25-
arrObj: formData.arrObj.map((v) => {
26-
v.o = parseFloat(v.o) ** 2;
27+
arr: formData.arr.map((v) => parseFloat(v) + 1),
28+
arrObj: formData.arrObj.map((v) => {
29+
v.o = parseFloat(v.o) ** 2;
2730

28-
return v;
29-
}),
30-
})}
31+
return v;
32+
}),
33+
};
34+
}}
3135
>
3236
<div className="form-group">
3337
<label htmlFor="">Obj</label>
@@ -81,7 +85,15 @@ function FormVersion() {
8185
}
8286

8387
function FormArray() {
84-
const { getValue } = useFormControl2('arr');
88+
const { getValue, setValue } = useFormControl2('arr');
89+
90+
useEffect(() => {
91+
setValue((prev) => {
92+
console.log('useEffect.setValue [arr] :>> ', prev, getValue());
93+
94+
return prev;
95+
});
96+
}, [getValue, setValue]);
8597

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

src/forms2/helpers/useFormControl.jsx

+9-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,15 @@ export function useFormControl2(name, type) {
99

1010
const setValue = useCallback(
1111
(newValue) => {
12-
_setValue(newValue);
13-
formHelper.notify(name, newValue);
12+
const newValueFn = isFunction(newValue) ? newValue : () => newValue;
13+
14+
_setValue((prevValue) => {
15+
const nextValue = newValueFn(prevValue);
16+
17+
formHelper.notify(name, nextValue);
18+
19+
return nextValue;
20+
});
1421
},
1522
[formHelper, name]
1623
);

0 commit comments

Comments
 (0)