All files / src/features/setting/hooks use-setting-form.ts

100% Statements 24/24
100% Branches 5/5
100% Functions 8/8
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                  7x       113x 113x   113x                 113x 15x 15x     113x 113x   113x 44x 75x   13x 13x 13x 8x 6x       5x 5x 5x       2x           113x                                    
import { useState, useMemo } from 'react';
import type { UseFormProps, FieldValues } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { createSafeZodResolver } from '@/lib/form-utils';
 
interface UseSettingFormOptions<T extends FieldValues> extends UseFormProps<T> {
  successMessage?: string;
}
 
export const useSettingForm = <T extends FieldValues>(
  schema: any,
  options: UseSettingFormOptions<T> = {}
) => {
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
 
  const form = useForm<T>({
    resolver: createSafeZodResolver(schema),
    mode: 'onSubmit', // Validate only on form submission
    reValidateMode: 'onChange', // After first validation, revalidate on change
    shouldFocusError: true,
    shouldUnregister: false,
    ...options,
  });
 
  const clearMessages = () => {
    setError(null);
    setSuccess(null);
  };
 
  const dismissError = () => setError(null);
  const dismissSuccess = () => setSuccess(null);
 
  const handleFormSubmit = useMemo(() => {
    return (submitFunction: (data: T) => Promise<void>) => {
      return form.handleSubmit(
        async data => {
          try {
            clearMessages();
            await submitFunction(data as T);
            if (options.successMessage) {
              setSuccess(options.successMessage);
            }
          } catch (err) {
            const errorMessage =
              err instanceof Error ? err.message : 'An error occurred';
            setError(errorMessage);
            throw new Error(errorMessage);
          }
        },
        errors => {
          console.log('Form validation FAILED:', Object.keys(errors));
        }
      );
    };
  }, [form, options.successMessage]);
 
  return {
    form,
    error,
    success,
    setError,
    setSuccess,
    clearMessages,
    dismissError,
    dismissSuccess,
    handleFormSubmit,
    control: form.control,
    formState: form.formState,
    setValue: form.setValue,
    getValues: form.getValues,
    reset: form.reset,
    watch: form.watch,
  };
};