Skip to content

Commit 41ea647

Browse files
committed
feat(forms): allow form data transformation after each input change
1 parent f42750e commit 41ea647

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

demo/FormExamples.jsx

+5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ export function FormExamples() {
2121
// return Promise.resolve();
2222
reset();
2323
}}
24+
transform={(formData) => {
25+
formData.__v = formData.__v ? formData.__v + 1 : 1;
26+
27+
return formData;
28+
}}
2429
onCancel={() => console.log('onCancel')}
2530
customValidation={true}
2631
validations={{

src/forms/Form.jsx

+6-3
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ export function Form({
1515
onChange,
1616
submitLabel,
1717
validations,
18+
transform,
1819
}) {
19-
const formState = useForm(initialValues, validations, onChange);
20+
const formState = useForm(initialValues, { validations, onChange, transform });
2021
const formRef = useRef(null);
2122

2223
function resetForm() {
@@ -69,17 +70,19 @@ Form.defaultProps = {
6970
cancelLabel: 'Cancel',
7071
customValidation: false,
7172
submitLabel: 'Submit',
73+
transform: (data) => data,
7274
};
7375

7476
Form.propTypes = {
7577
cancelLabel: PropTypes.string,
7678
children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]),
77-
customValidation: PropTypes.bool,
7879
customActions: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]),
80+
customValidation: PropTypes.bool,
7981
initialValues: PropTypes.object,
8082
onCancel: PropTypes.func,
81-
onSubmit: PropTypes.func.isRequired,
8283
onChange: PropTypes.func,
84+
onSubmit: PropTypes.func.isRequired,
8385
submitLabel: PropTypes.string,
86+
transform: PropTypes.func,
8487
validations: PropTypes.object,
8588
};

src/forms/helpers/useForm.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { setValueByPath, deepClone, getValueByPath } from '../../utils/getters-s
44
import { validateFormElement } from './form-helpers';
55
import { debounce } from 'lodash-es';
66

7-
export function useForm(initialState, validations, onChange) {
7+
export function useForm(initialState, { validations, onChange, transform }) {
88
const [formState, setFormState] = useState(initialState);
99
const [submitAttempted, setSubmitAttempted] = useState(false);
1010
const { getAllKeys: getElementNames, get: getElementRefs, push: registerElementRef } = useArrayValueMap();
@@ -31,7 +31,7 @@ export function useForm(initialState, validations, onChange) {
3131
}
3232
},
3333
update(name, value) {
34-
setFormState((prevFormState) => nextState(prevFormState, name, value));
34+
setFormState((prevFormState) => transform(nextState(prevFormState, name, value), name));
3535

3636
if (validations) {
3737
this.validateForm(nextState(formState, name, value));

0 commit comments

Comments
 (0)