-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseForm.tsx
52 lines (41 loc) · 1.38 KB
/
useForm.tsx
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
50
51
52
import './locale';
import { useCallback } from 'react';
import {
useForm as useFormHook,
UseFormProps,
useFieldArray as useFieldArrayHook,
UseFormReturn as HookUseFormReturn,
FieldValues,
UseFormReset
} from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
type Yup = typeof yup;
export interface UseFormParams<T extends FieldValues> extends UseFormProps<T> {
validationSchema?: yup.Schema<T> | ((yup: Yup) => yup.Schema<T>) | undefined;
}
export type FormModel<Form> = Form extends HookUseFormReturn<infer M> ? M : Form;
export interface UseFormReturn<T extends FieldValues> extends HookUseFormReturn<T, any> {
setValues: UseFormReset<T>;
}
/**
* Hook implemation of react-hook-form with Yup
* @param UseFormParams
*/
export default function useForm<T extends FieldValues>({
validationSchema,
...params
}: UseFormParams<T>): UseFormReturn<T> {
if (validationSchema) {
Object.assign(params, {
resolver: yupResolver(typeof validationSchema === 'function' ? validationSchema(yup) : (validationSchema as any))
});
}
const form = useFormHook<T>(params);
const setValues = useCallback<UseFormReset<T>>(
(values, keepStateOptions = {}) => form.reset(values, { keepDefaultValues: true, ...keepStateOptions }),
[form]
);
return { ...form, setValues };
}
export const useFieldArray = useFieldArrayHook;