All files / src/components/Recipe/Create/hooks useFormError.ts

0% Statements 0/8
0% Branches 0/4
0% Functions 0/3
0% Lines 0/8

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                                                                           
import type { UseFormReturnType } from '@mantine/form';
import { useCallback } from 'react';
import type { RecipeFormValues } from '../types';
 
/**
 * Helper hook that provides error-checking utilities for the recipe form.
 * This replaces the old Formik-based useFormikError hook.
 *
 * Expects the form instance to be passed directly — the Recipe Composer
 * passes it through its context or props.
 */
export const useFormError = (form: UseFormReturnType<RecipeFormValues>) => {
  const getFieldError = useCallback(
    (path: string): string | undefined => {
      const error = form.errors[path];
      return typeof error === 'string' ? error : undefined;
    },
    [form.errors],
  );
 
  /**
   * Call this inside an onChange handler.
   * It re-validates only the single field — but only when it already has an
   * error. This way the error clears immediately once the user types a valid
   * value, without running the full schema on every keystroke for pristine fields.
   */
  const revalidateOnChange = useCallback(
    (path: string) => {
      if (form.errors[path]) {
        form.validateField(path);
      }
    },
    [form],
  );
 
  return { getFieldError, revalidateOnChange };
};