UNPKG

@matthew.ngo/reform

Version:

A flexible and powerful React form management library with advanced validation, state observation, and multi-group support

73 lines (67 loc) 1.87 kB
import { UseFormReturn } from "react-hook-form"; import { FormGroup } from "./form-groups"; interface UseFormResetProps<T> { methods: UseFormReturn<any>; defaultData: T; minGroups: number; } /** * Hook for advanced form reset functionality * * @param props - Hook properties * @returns Object with reset methods */ export const useFormReset = <T extends Record<string, any>>({ methods, defaultData, minGroups, }: UseFormResetProps<T>) => { /** * Resets the form to its initial state or to provided default values */ const resetForm = ( defaultValues?: { groups: FormGroup<T>[] }, options?: { keepDirty?: boolean; keepErrors?: boolean; keepValues?: boolean; keepIsSubmitted?: boolean; keepTouched?: boolean; } ) => { methods.reset(defaultValues, options); }; /** * Resets the form to a clean state with the specified number of groups * * @param groupCount - Number of groups to initialize (defaults to minGroups) */ const resetToCleanState = (groupCount: number = minGroups) => { const cleanGroups = Array.from({ length: groupCount }).map(() => ({ id: Math.random().toString(36).substr(2, 9), data: { ...defaultData }, })); methods.reset({ groups: cleanGroups as FormGroup<T>[] }); }; /** * Resets a specific group to its default state * * @param index - Index of the group to reset */ const resetGroup = (index: number) => { const currentGroups = methods.getValues().groups; if (index >= 0 && index < currentGroups.length) { const updatedGroups = [...currentGroups]; updatedGroups[index] = { id: updatedGroups[index].id, data: { ...defaultData }, }; methods.reset({ groups: updatedGroups }); } }; return { resetForm, resetToCleanState, resetGroup, }; };