| 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
 | import { useCallback, useState } from 'react';
import type { DataValidator, Nullable } from '../../../types';
import {
  type FormSubmitHandler,
  useFormSubmit,
  type UseFormSubmitReturn,
} from './use-form-submit';
import { type UseFormValuesReturn, useFormValues } from './use-form-values';
export type FormFieldValidation<T> = {
  /**
   * The error message.
   */
  error: string;
  /**
   * A function to validate the field value.
   */
  validator: DataValidator<T>;
};
export type FormValidations<T> = {
  [K in keyof T]: FormFieldValidation<T[K]>;
};
export type FormValidationErrors<T> = {
  [K in keyof T]?: string;
};
export type UseFormConfig<T> = {
  /**
   * The initial fields values.
   */
  initialValues: T;
  /**
   * A function to handle submit.
   */
  submitHandler?: FormSubmitHandler<T>;
  /**
   * An object with validator and error message to validate each field.
   */
  validations?: Partial<FormValidations<T>>;
};
export type UseFormReturn<T extends Record<string, unknown>> =
  UseFormValuesReturn<T> &
    UseFormSubmitReturn & {
      /**
       * The validation error for each field.
       */
      validationErrors: Nullable<FormValidationErrors<T>>;
    };
/**
 * React hook to manage forms.
 *
 * @template {object} T - The object keys should match the fields name.
 * @param {UseFormConfig<T>} config - The config.
 * @returns {UseFormReturn<T>} The values, validations errors and form methods.
 */
export const useForm = <T extends Record<string, unknown>>({
  initialValues,
  submitHandler,
  validations,
}: UseFormConfig<T>): UseFormReturn<T> => {
  const { values, reset, update } = useFormValues(initialValues);
  const [validationErrors, setValidationErrors] =
    useState<Nullable<FormValidationErrors<T>>>(null);
  const areValuesValid = useCallback(async () => {
    if (!validations) return true;
    const keys = Object.keys(values) as Extract<keyof T, string>[];
    const validationPromises = keys.map(async (key) => {
      const value = values[key];
      const field = validations[key];
      if (!field) return true;
      const isValidField = await field.validator(value);
      if (!isValidField)
        setValidationErrors((prevErr) => {
          const newErrors: FormValidationErrors<T> = prevErr
            ? { ...prevErr }
            : {};
          return {
            ...newErrors,
            [key]: field.error,
          };
        });
      return isValidField;
    });
    const awaitedValidation = await Promise.all(validationPromises);
    return awaitedValidation.every((isValid) => isValid);
  }, [validations, values]);
  const handleSubmit = useCallback(async () => {
    setValidationErrors(null);
    const isValid = await areValuesValid();
    if (isValid && submitHandler) return submitHandler(values);
    return {
      validator: () => isValid,
      messages: {
        error: 'Has invalid values',
      },
    };
  }, [areValuesValid, submitHandler, values]);
  const handleSuccess = useCallback(() => {
    reset();
  }, [reset]);
  const { messages, submit, submitStatus } = useFormSubmit(values, {
    onSuccess: handleSuccess,
    submit: handleSubmit,
  });
  return {
    messages,
    reset,
    submit,
    submitStatus,
    update,
    values,
    validationErrors,
  };
};
 |