import { ChangeEvent, FormEvent } from "react"; /** * Validation function type */ type ValidatorFunction = (name: keyof T, value: any, values: T) => string | undefined; /** * Options for the useFormState hook */ interface UseFormStateOptions { /** * Initial form values */ initialValues: T; /** * Validation function */ validate?: ValidatorFunction; /** * Callback when form is submitted with valid data */ onSubmit?: (values: T) => void | Promise; } /** * Return value for the useFormState hook */ interface UseFormStateReturnValue { /** * Current form values */ values: T; /** * Validation errors for each field */ errors: Partial>; /** * Touched state for each field */ touched: Partial>; /** * Whether the form is currently submitting */ isSubmitting: boolean; /** * Whether the form is valid */ isValid: boolean; /** * Handle input change events */ handleChange: (event: ChangeEvent) => void; /** * Handle form submit events */ handleSubmit: (event: FormEvent) => void; /** * Set a specific field value */ setFieldValue: (name: keyof T, value: any) => void; /** * Set a specific field error */ setFieldError: (name: keyof T, error: string) => void; /** * Set a specific field as touched */ setFieldTouched: (name: keyof T, touched: boolean) => void; /** * Reset the form to initial values */ reset: () => void; } /** * useFormState hook * * Comprehensive form state management with validation and error handling. * Handles form values, errors, touched state, and submission. * * @param options - Configuration options for the form * @returns Object containing form state and handlers * * @example * ```tsx * import { useFormState } from "rooks"; * * interface LoginForm { * email: string; * password: string; * } * * function LoginComponent() { * const { * values, * errors, * touched, * isSubmitting, * isValid, * handleChange, * handleSubmit, * reset, * } = useFormState({ * initialValues: { email: "", password: "" }, * validate: (name, value, values) => { * if (name === "email" && !value.includes("@")) { * return "Invalid email"; * } * if (name === "password" && value.length < 6) { * return "Password must be at least 6 characters"; * } * }, * onSubmit: async (values) => { * await loginUser(values); * }, * }); * * return ( *
* * {touched.email && errors.email && {errors.email}} * * * {touched.password && errors.password && {errors.password}} * * * *
* ); * } * ``` * * @see https://rooks.vercel.app/docs/hooks/useFormState */ declare function useFormState>({ initialValues, validate, onSubmit, }: UseFormStateOptions): UseFormStateReturnValue; export { useFormState }; export type { UseFormStateOptions, UseFormStateReturnValue, ValidatorFunction, };