@matthew.ngo/reform
Version:
A flexible and powerful React form management library with advanced validation, state observation, and multi-group support
38 lines (34 loc) • 1.24 kB
text/typescript
import { UseFormReturn } from 'react-hook-form';
import { FormDataPath } from '../../types';
import { FormGroup } from './form-groups';
export const useFormState = <T extends Record<string, any>>(
methods: UseFormReturn<{ groups: FormGroup<T>[] }>
) => {
return {
fieldState: {
isDirty: (index: number, fieldName: keyof T) =>
methods.getFieldState(
`groups.${index}.data.${String(fieldName)}` as FormDataPath<T>
).isDirty,
isTouched: (index: number, fieldName: keyof T) =>
methods.getFieldState(
`groups.${index}.data.${String(fieldName)}` as FormDataPath<T>
).isTouched,
get: (index: number, fieldName: keyof T) =>
methods.getFieldState(
`groups.${index}.data.${String(fieldName)}` as FormDataPath<T>
),
},
formState: {
isDirty: methods.formState.isDirty,
isValid: methods.formState.isValid,
touched: Object.keys(methods.formState.touchedFields).length > 0,
isSubmitting: methods.formState.isSubmitting,
submitCount: methods.formState.submitCount,
isValidating: methods.formState.isValidating,
},
reset: methods.reset,
trigger: methods.trigger,
watch: methods.watch,
};
};