-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathuseForm.ts
More file actions
49 lines (43 loc) · 1.02 KB
/
Copy pathuseForm.ts
File metadata and controls
49 lines (43 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React from 'react';
import {
useFormik,
FormikValues,
FormikConfig,
FormikErrors,
FormikTouched,
} from 'formik';
export const useForm = <Values extends FormikValues = FormikValues>(
config: FormikConfig<Values>
) => {
const { errors, touched, values, isValid, dirty, ...formik } = useFormik(
config
);
const generateErrors = ({
values,
errors,
touched,
}: {
values: Values;
errors: FormikErrors<Values>;
touched: FormikTouched<Values>;
}) => {
let errorsMap: { [K in keyof Values]?: string } = {};
const valuesKeys = Object.keys(values);
if (valuesKeys.length) {
for (const key of valuesKeys) {
errorsMap = {
...errorsMap,
[key]: touched[key] && errors[key] ? errors[key] : null,
};
}
}
return errorsMap;
};
const isValidForm = React.useMemo(() => isValid && dirty, [isValid, dirty]);
return {
...formik,
errors: generateErrors({ errors, values, touched }),
isValidForm,
values,
};
};