Seriya: React Hook Form Dars 97

Large-scale Form Architecture — Katta loyihalarda form arxitekturasi

Katta va murakkab loyihalarda formani qatlamlarga ajratish: feature-based folder tuzilmasi, types, mappers, schemas, isolated sections va server error handling.

97-dars

Large-scale Form Architecture — Katta loyihalarda form arxitekturasi

Large-scale Form Architecture (katta miqyosli formalar arxitekturasi) — bu o'nlab maydonlar, bir nechta mantiqiy bo'limlar, murakkab biznes qoidalar va bir nechta rollarga ega bo'lgan korporativ (Enterprise, CRM, ERP, FinTech) loyihalarda formalarni modulli, kengaytiriladigan (scalable), oson testlanadigan va texnik qarzlarsiz tashkil etish tizimidir.

Katta loyihalarda eng ko'p uchraydigan halokatli xato — formaning barcha TypeScript turlarini, validatsiya qoidalarini, API so'rovlarini, server xatolarini qayta ishlash mantiqini va o'nlab input JSX bloklarini bitta ulkan (1000+ qatorli) faylga tiqib qo'yishdir ("God Component" anti-patterni).

Buning o'rniga mas'uliyatlarni aniq qatlamlarga ajratuvchi Feature-based arxitektura qo'llaniladi.


1. Feature-based Papkalar Tuzilmasi

Katta loyihalarda har bir forma alohida feature moduli sifatida shakllantiriladi:

src/
  features/
    employees/
      types/
        employee-form.types.ts      # UI FormValues, API Payload va ServerError tiplari
      schemas/
        employee-form.schema.ts     # Validatsiya qoidalari (Zod / Yup yoki RHF qoidalari)
      mappers/
        employee-form.mapper.ts     # FormValues <-> ApiPayload transformatsiyasi va xatolarni bog'lash
      api/
        employee-form.api.ts        # Axios so'rovlari (createEmployee, updateEmployee)
      components/
        EmployeeForm.tsx            # Asosiy Forma (<FormProvider> + submit orkestratsiyasi)
        EmployeeIdentitySection.tsx # Mustaqil bo'lim 1 (Ism, Email, Bo'lim)
        EmployeeEquipmentSection.tsx# Mustaqil bo'lim 2 (Noutbuk va texnika)
      index.ts                      # Tashqi dunyo uchun public eksportlar
  routes/
    employees.new.tsx               # Yupqa (thin) sahifa: faqat API hook va Formani ulaydi

2. Mas'uliyatlar Oqimi (Architecture Workflow)

graph TD
  A["Page / Route (Yupqa qatlam)"] -->|Boshlang'ich qiymatlar| B["EmployeeForm (State & Orchestration)"]
  B --> C["FormProvider (Context Bridge)"]
  C --> D["EmployeeIdentitySection (UI & register)"]
  C --> E["EmployeeEquipmentSection (useWatch izolyatsiyasi)"]
  
  B -->|Foydalanuvchi Submit bosdi| F["toSaveEmployeePayload() Mapper"]
  F -->|Toza API DTO| G["employeeApi.create() (Axios)"]
  G -->|Muvaffaqiyat (200 OK)| H["onSuccess callback / Redirect"]
  G -->|Xatolik (422 / 400)| I["applyEmployeeServerErrors() Mapper"]
  I -->|setError('field', ...)| B

Arxitekturaviy Qoidalar:

  1. Yupqa Route/Page qatlami: Sahifa faylida (masalan, Next.js yoki TanStack Router sahifalarida) katta form kodi yozilmaydi — u faqat kerakli API mutatsiyasini va formani ulaydi.
  2. Sof funksiyalar (Pure Mappers): Ma'lumotlarni o'zgartirish (mapper) funksiyalari React yoki JSX dan mutlaqo holi bo'ladi. Ularni 100% unit testlar bilan qoplash juda oson.
  3. Izolyatsiya qilingan bo'limlar: Har bir bo'lim faqat o'ziga tegishli maydonlar va holatlarga obuna bo'ladi.

3. To'liq amaliy misol: Katta Xodimlar Formasi

Quyidagi amaliy misolda arxitekturaning barcha qatlamlari real TypeScript kodida qanday bog'lanishi ko'rsatilgan:

import React, { useRef } from "react";
import axios from "axios";
import {
  FormProvider,
  useForm,
  useFormContext,
  useWatch,
  type UseFormSetError,
  type SubmitHandler,
} from "react-hook-form";

// ==========================================
// 1. types/employee-form.types.ts
// ==========================================
export type EmployeeFormValues = {
  fullName: string;
  email: string;
  department: "engineering" | "product" | "hr";
  hasCompanyLaptop: boolean;
  laptopSerial: string;
};

export type SaveEmployeeApiPayload = {
  full_name: string;
  email: string;
  department: "engineering" | "product" | "hr";
  laptop_serial: string | null;
};

export type BackendValidationError = {
  message?: string;
  errors?: Partial<Record<keyof EmployeeFormValues, string>>;
};

// ==========================================
// 2. mappers/employee-form.mapper.ts
// ==========================================
// UI Form ma'lumotlarini Backend API formatiga (DTO) o'girish
export function toSaveEmployeePayload(
  values: EmployeeFormValues
): SaveEmployeeApiPayload {
  return {
    full_name: values.fullName.trim(),
    email: values.email.trim().toLowerCase(),
    department: values.department,
    laptop_serial: values.hasCompanyLaptop
      ? values.laptopSerial.trim() || null
      : null,
  };
}

// Backenddan kelgan xatolarni RHF maydonlariga bog'lash
export function applyEmployeeServerErrors(
  errorData: BackendValidationError | undefined,
  setError: UseFormSetError<EmployeeFormValues>
) {
  const fieldErrors = errorData?.errors;
  let mappedAny = false;

  if (fieldErrors) {
    (
      Object.entries(fieldErrors) as [keyof EmployeeFormValues, string | undefined][]
    ).forEach(([field, message], idx) => {
      if (message) {
        setError(field, { type: "server", message }, { shouldFocus: idx === 0 });
        mappedAny = true;
      }
    });
  }

  // Agar aniq maydon xatosi bo'lmasa yoki umumiy xabar kelsa
  if (!mappedAny || errorData?.message) {
    setError("root.serverError", {
      type: "server",
      message:
        errorData?.message || "Server bilan aloqada kutilmagan xatolik yuz berdi.",
    });
  }
}

// Re-render hisoblagich nishoni
function RenderBadge({ name }: { name: string }) {
  const count = useRef(0);
  count.current += 1;
  return (
    <span className="text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono">
      {name}: {count.current} render
    </span>
  );
}

// ==========================================
// 3. components/EmployeeIdentitySection.tsx
// ==========================================
function EmployeeIdentitySection() {
  const {
    register,
    formState: { errors },
  } = useFormContext<EmployeeFormValues>();

  return (
    <section className="border border-gray-200 bg-white p-5 rounded-xl shadow-sm space-y-4">
      <div className="flex items-center justify-between border-b pb-2">
        <h3 className="font-semibold text-gray-800">1. Asosiy Ma'lumotlar</h3>
        <RenderBadge name="IdentitySection" />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          To'liq ism *
        </label>
        <input
          {...register("fullName", { required: "To'liq ismni kiritish shart" })}
          placeholder="Masalan: Sardorbek Aliyev"
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
        />
        {errors.fullName && (
          <p className="text-xs text-rose-500 mt-1">{errors.fullName.message}</p>
        )}
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Ish emaili *
        </label>
        <input
          type="email"
          {...register("email", {
            required: "Email kiritish shart",
            pattern: {
              value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/,
              message: "Email formati noto'g'ri",
            },
          })}
          placeholder="[email protected]"
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
        />
        {errors.email && (
          <p className="text-xs text-rose-500 mt-1">{errors.email.message}</p>
        )}
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Bo'lim
        </label>
        <select
          {...register("department")}
          className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none bg-white"
        >
          <option value="engineering">Muhandislik (Engineering)</option>
          <option value="product">Mahsulot (Product)</option>
          <option value="hr">Inson resurslari (HR)</option>
        </select>
      </div>
    </section>
  );
}

// ==========================================
// 4. components/EmployeeEquipmentSection.tsx
// ==========================================
function EmployeeEquipmentSection() {
  const {
    register,
    control,
    formState: { errors },
  } = useFormContext<EmployeeFormValues>();

  // Faqat hasCompanyLaptop o'zgarganda bu bo'lim yangilanadi
  const hasCompanyLaptop = useWatch({
    control,
    name: "hasCompanyLaptop",
  });

  return (
    <section className="border border-gray-200 bg-white p-5 rounded-xl shadow-sm space-y-4">
      <div className="flex items-center justify-between border-b pb-2">
        <h3 className="font-semibold text-gray-800">2. Texnika Ta'minoti</h3>
        <RenderBadge name="EquipmentSection" />
      </div>

      <label className="flex items-center gap-3 cursor-pointer">
        <input
          type="checkbox"
          {...register("hasCompanyLaptop")}
          className="w-4 h-4 text-blue-600 rounded"
        />
        <span className="text-sm font-medium text-gray-700">
          Xodimga korporativ noutbuk biriktirilsin
        </span>
      </label>

      {/* Shartli maydon: Noutbuk belgilanmagan bo'lsa ko'rinmaydi */}
      {hasCompanyLaptop && (
        <div className="pt-2 border-t border-dashed border-gray-200">
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Noutbuk seriya raqami *
          </label>
          <input
            {...register("laptopSerial", {
              required: "Noutbuk tanlangan bo'lsa seriya raqami kiritilishi shart",
            })}
            placeholder="Masalan: SN-MAC-2026-098"
            className="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none font-mono"
          />
          {errors.laptopSerial && (
            <p className="text-xs text-rose-500 mt-1">{errors.laptopSerial.message}</p>
          )}
        </div>
      )}
    </section>
  );
}

// ==========================================
// 5. components/EmployeeForm.tsx (Orkestratsiya)
// ==========================================
type EmployeeFormProps = {
  initialValues?: EmployeeFormValues;
  onSuccess?: () => void;
};

const DEFAULT_EMPLOYEE_VALUES: EmployeeFormValues = {
  fullName: "",
  email: "",
  department: "engineering",
  hasCompanyLaptop: false,
  laptopSerial: "",
};

export function EmployeeForm({
  initialValues = DEFAULT_EMPLOYEE_VALUES,
  onSuccess,
}: EmployeeFormProps) {
  const methods = useForm<EmployeeFormValues>({
    mode: "onBlur",
    defaultValues: initialValues,
  });

  const {
    handleSubmit,
    setError,
    reset,
    formState: { errors, isSubmitting },
  } = methods;

  const onSubmit: SubmitHandler<EmployeeFormValues> = async (values) => {
    // 1. UI formatidagi qiymatlarni API DTO formatiga o'giramiz
    const payload = toSaveEmployeePayload(values);

    try {
      // Simulyatsiya qilingan API chaqiruv
      console.log("Serverga POST payload jo'natilmoqda:", payload);
      await new Promise((resolve) => setTimeout(resolve, 800));

      // Muvaffaqiyatli yakun
      reset(DEFAULT_EMPLOYEE_VALUES);
      alert("Xodim muvaffaqiyatli saqlandi!");
      onSuccess?.();
    } catch (error) {
      if (axios.isAxiosError<BackendValidationError>(error)) {
        applyEmployeeServerErrors(error.response?.data, setError);
      } else {
        setError("root.serverError", {
          type: "unknown",
          message: "Tarmoq bilan aloqada kutilmagan nosozlik yuz berdi.",
        });
      }
    }
  };

  return (
    <div className="max-w-xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-gray-900">Yangi Xodim Ro'yxati</h2>
        <RenderBadge name="EmployeeForm" />
      </div>

      <FormProvider {...methods}>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          {/* Umumiy server xatosi xabari */}
          {errors.root?.serverError && (
            <div className="p-3 bg-rose-50 border border-rose-300 rounded-lg text-sm text-rose-700">
              {errors.root.serverError.message}
            </div>
          )}

          <EmployeeIdentitySection />
          <EmployeeEquipmentSection />

          <button
            type="submit"
            disabled={isSubmitting}
            className="w-full py-2.5 px-4 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-medium rounded-lg transition"
          >
            {isSubmitting ? "Saqlanmoqda..." : "Xodimni tizimga kiritish"}
          </button>
        </form>
      </FormProvider>
    </div>
  );
}

4. Katta Loyihalardagi Oltin Qoidalar

  1. Bitta mas'uliyat — bitta fayl (SRP):
    • DTO tuzish mantiqi mapper faylida.
    • Validatsiya qoidalari schema faylida.
    • API chaqiruvi api faylida.
    • UI bo'limlari components papkasida.
  2. Oson Unit Testlash: toSaveEmployeePayload funksiyasini test qilish uchun React render qilish yoki brauzer ochish umuman shart emas — oddiy JavaScript obyektini berib, natijani expect() bilan tekshirish kifoya.
  3. Qo'shilish osonligi (Maintainability): Yangi dasturchi jamoaga qo'shilganda ming qatorlik faylni titkilab o'tirmaydi; faqat kerakli bo'lim faylini ochib tezda o'zgartirish kirita oladi.

Xulosa

  • Feature-based qatlamlar: Katta formalarni alohida turlarga, xaritalovchi (mapper) funksiyalarga va izolyatsiyalangan UI bo'limlariga ajratish katta loyihalarning asosiy talabidir.
  • FormProvider + Sections: Props drilling muammosini yo'qotadi va bo'limlarni bir-biridan mustaqil qilib qo'yadi.
  • Server Error Mapping: Backenddan qaytgan xatolarni avtomatik tarzda tegishli input ostida ko'rsatuvchi alohida mapper yozish formaning ishonchliligini oshiradi.