Seriya: React Hook Form Dars 74

update() — Array elementini yangilash

useFieldArray ichida update(index, value) orqali ma'lum bir elementni yangilash, getValues() bilan eng dolzarb qiymatni olish va setValue dan farqlari.

74-dars

update() — Array elementini yangilash

useFieldArray() hooki taqdim etadigan update(index, value) metodi dinamik massivdagi ma'lum bir indexda joylashgan elementni to'liq yangi obyekt bilan almashtirib yangilash uchun ishlatiladi.

Foydalanuvchi oddiy hollarda inputga matn yozganda qiymat register() orqali o'zgaradi. Ammo dasturiy ravishda — masalan, "Standart qiymatga qaytarish", "Katalogdan tanlangan ma'lumotni to'ldirish" yoki "Avtomatik hisoblab narxni belgilash" kabi amallarda aynan update() metodi qo'l keladi.


1. update() vs setValue() vs replace()

Metod Qamrovi Yangilanish shakli Qachon ishlatiladi?
update(index, value) Faqat ko'rsatilgan indexdagi qator To'liq yangi qator obyekti Bitta qatorning bir nechta maydonini birdan yangilash yoki qatorni qayta hisoblashda.
setValue("items.0.price", 100) Bitta aniq maydon (field path) Yagona qiymat Qatorning faqat bitta inputini dasturiy o'zgartirishda.
replace(newArray) Butun dinamik massiv Barcha qatorlar massivi Shablon yuklash yoki butun ro'yxatni almashtirishda.

2. update() bilan ishlashda eng muhim qoidalar

1. field obyektiga emas, getValues() ga tayaning

useFieldArray qaytaradigan fields massivi foydalanuvchi inputga yozgan har bir harfida qayta render bo'lmaydi (chunki uncontrolled inputlar yuqori tezlikni ta'minlaydi).

Agar foydalanuvchi inputga yangi ism yozgan bo'lsa va siz field.employeeName ni olsangiz, u eski (boshlang'ich) qiymatni berishi mumkin. Eng dolzarb qiymatni olish uchun har doim getValues() dan foydalaning:

// ❌ Noto'g'ri: fields ichidagi eski holatni olish
const handleUpdateOld = (index: number) => {
  const oldField = fields[index]; // Foydalanuvchi yaqinda yozgan matn tushib qolishi mumkin!
  update(index, { ...oldField, hours: "8" });
};

// ✅ To'g'ri: getValues orqali eng oxirgi kiritilgan holatni olish
const handleUpdateFresh = (index: number) => {
  const currentRow = getValues(`shifts.${index}`);
  update(index, {
    ...currentRow,
    hours: "8",
  });
};

2. To'liq obyekt uzating (Partial Patch emas)

update(index, value) obyekti qisman o'zgartirish (partial update) kiritmaydi, balki o'sha qatorni to'liq yangi obyekt bilan almashtiradi. Shuning uchun o'zgarmas maydonlarni doimo spread (...currentRow) qilib uzatish shart:

// ❌ Xato: role va employeeName maydonlari o'chib ketadi!
update(index, { hours: "8" });

// ✅ To'g'ri: Mavjud maydonlar saqlanadi
update(index, { ...currentRow, hours: "8" });

3. Real misol: Ish vaqti tabeli (Timesheet Form)

Quyidagi misolda xodimlarning ish vaqti tabeli keltirilgan. Har bir qator uchun "8 soat (Standart)" va "Katalogdan QA qilish" tugmalari mavjud bo'lib, ular update() orqali ma'lumotlarni bir zumda yangilaydi:

import React from "react";
import { useForm, useFieldArray, type SubmitHandler } from "react-hook-form";

// 1. Tiplar
type ShiftItem = {
  employeeName: string;
  role: string;
  hours: string;
};

type TimesheetFormValues = {
  date: string;
  shifts: ShiftItem[];
};

export function TimesheetUpdateForm() {
  const {
    register,
    control,
    handleSubmit,
    getValues,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<TimesheetFormValues>({
    defaultValues: {
      date: "2026-11-20",
      shifts: [
        { employeeName: "Jasur Karimov", role: "Frontend", hours: "4" },
        { employeeName: "Madina Rasulova", role: "QA Engineer", hours: "6" },
      ],
    },
  });

  const { fields, update, append, remove } = useFieldArray({
    control,
    name: "shifts",
  });

  // Standart 8 soatlik smenani belgilash
  const handleApplyStandardHours = (index: number) => {
    // getValues orqali eng oxirgi kiritilgan holatni olamiz
    const currentRow = getValues(`shifts.${index}`);
    update(index, {
      ...currentRow,
      hours: "8",
    });
  };

  // Rol va standart vaqtni avtomatik to'ldirish
  const handlePromoteToLead = (index: number) => {
    const currentRow = getValues(`shifts.${index}`);
    update(index, {
      ...currentRow,
      role: "Team Lead",
      hours: "8",
    });
  };

  const onSubmit: SubmitHandler<TimesheetFormValues> = async (data) => {
    await new Promise((resolve) => setTimeout(resolve, 300));
    console.log("Yuborilgan tabel ma'lumotlari:", data);
    alert(`Tabel saqlandi! Xodimlar soni: ${data.shifts.length}`);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate style={{ maxWidth: "680px" }}>
      {/* Sana tanlash */}
      <div style={{ marginBottom: "16px" }}>
        <label htmlFor="date" style={{ display: "block", fontWeight: 600, marginBottom: "4px" }}>
          Sana *
        </label>
        <input
          id="date"
          type="date"
          {...register("date", { required: "Sanani tanlang" })}
          style={{ padding: "6px 10px" }}
        />
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
        <h4 style={{ margin: 0 }}>Xodimlar smenasi ro'yxati</h4>
        <button
          type="button"
          onClick={() => append({ employeeName: "", role: "Frontend", hours: "8" })}
          style={{
            padding: "6px 12px",
            background: "#10b981",
            color: "#fff",
            border: "none",
            borderRadius: "4px",
            cursor: "pointer",
          }}
        >
          + Xodim qo'shish
        </button>
      </div>

      {/* Qatorlar ro'yxati */}
      <div style={{ display: "flex", flexDirection: "column", gap: "10px", marginBottom: "20px" }}>
        {fields.map((field, index) => {
          const nameError = errors.shifts?.[index]?.employeeName;

          return (
            <div
              key={field.id}
              style={{
                display: "flex",
                flexWrap: "wrap",
                alignItems: "center",
                gap: "8px",
                padding: "10px",
                background: "#f8fafc",
                borderRadius: "6px",
                border: "1px solid #e2e8f0",
              }}
            >
              {/* Xodim ismi */}
              <div style={{ flex: "2 1 180px" }}>
                <input
                  {...register(`shifts.${index}.employeeName` as const, {
                    required: "Ism majburiy",
                  })}
                  placeholder="Xodim ismi"
                  style={{
                    width: "100%",
                    padding: "6px 8px",
                    boxSizing: "border-box",
                    borderColor: nameError ? "#e11d48" : "#cbd5e1",
                    borderWidth: "1px",
                    borderRadius: "4px",
                  }}
                  aria-invalid={Boolean(nameError)}
                />
              </div>

              {/* Lavozim/Rol */}
              <div style={{ flex: "1 1 120px" }}>
                <input
                  {...register(`shifts.${index}.role` as const)}
                  placeholder="Lavozim"
                  style={{ width: "100%", padding: "6px 8px", boxSizing: "border-box" }}
                />
              </div>

              {/* Ish soati */}
              <div style={{ flex: "0 0 70px" }}>
                <input
                  type="number"
                  {...register(`shifts.${index}.hours` as const, {
                    required: "Soat kiritilishi shart",
                    min: { value: 1, message: "Kamida 1 soat" },
                    max: { value: 24, message: "Ko'pi bilan 24 soat" },
                  })}
                  placeholder="Soat"
                  style={{ width: "100%", padding: "6px 8px", boxSizing: "border-box" }}
                />
              </div>

              {/* update() chaqiruvchi tugmalar */}
              <button
                type="button"
                onClick={() => handleApplyStandardHours(index)}
                title="8 soat qilib yangilash"
                style={{
                  padding: "5px 10px",
                  background: "#3b82f6",
                  color: "#fff",
                  border: "none",
                  borderRadius: "4px",
                  cursor: "pointer",
                  fontSize: "12px",
                }}
              >
                8 soat (update)
              </button>

              <button
                type="button"
                onClick={() => handlePromoteToLead(index)}
                title="Team Lead va 8 soat etib yangilash"
                style={{
                  padding: "5px 10px",
                  background: "#8b5cf6",
                  color: "#fff",
                  border: "none",
                  borderRadius: "4px",
                  cursor: "pointer",
                  fontSize: "12px",
                }}
              >
                Lead qilish
              </button>

              {/* O'chirish */}
              {fields.length > 1 && (
                <button
                  type="button"
                  onClick={() => remove(index)}
                  title="Qatorni o'chirish"
                  style={{
                    padding: "5px 8px",
                    background: "#ef4444",
                    color: "#fff",
                    border: "none",
                    borderRadius: "4px",
                    cursor: "pointer",
                  }}
                >
                  ✕
                </button>
              )}

              {nameError && (
                <p role="alert" style={{ width: "100%", color: "#e11d48", fontSize: "12px", margin: "2px 0 0 4px" }}>
                  {nameError.message}
                </p>
              )}
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", gap: "10px" }}>
        <button
          type="submit"
          disabled={isSubmitting}
          style={{
            padding: "10px 20px",
            background: "#2563eb",
            color: "#fff",
            border: "none",
            borderRadius: "6px",
            cursor: isSubmitting ? "not-allowed" : "pointer",
            fontWeight: 600,
          }}
        >
          {isSubmitting ? "Saqlanmoqda..." : "Tabelni saqlash"}
        </button>

        <button
          type="button"
          onClick={() => reset()}
          style={{
            padding: "10px 16px",
            background: "#f1f5f9",
            color: "#475569",
            border: "1px solid #cbd5e1",
            borderRadius: "6px",
            cursor: "pointer",
          }}
        >
          Qayta tiklash
        </button>
      </div>
    </form>
  );
}

4. Xulosa va eslatmalar

  1. update() afzalligi: Massivning barcha boshqa elementlariga daxl qilmasdan, aynan kerakli indeksdagi qatorni xavfsiz va to'liq almashtiradi.
  2. getValues() bilan sinxronlik: Foydalanuvchi klaviaturada kiritgan eng yangi o'zgarishlarni yo'qotib qo'ymaslik uchun fields[index] dan emas, balki getValues(arrayName.${index}) dan foydalaning.
  3. Spread operatori (...): Barcha qolgan maydonlarni saqlab qolish uchun yangilanayotgan obyektga eski ma'lumotlarni to'liq yoying.