Khoá học web cho nhà máy, bài 8: React nâng cao với API thật, form và bảng phân trang
Dùng TanStack Query để tải và đồng bộ dữ liệu, viết form có kiểm tra dữ liệu, bảng phân trang tìm kiếm phía máy chủ, hộp thoại thêm sửa xoá thiết bị và xử lý trạng thái đang tải, lỗi, rỗng.
Bài 3 dùng dữ liệu giả. Bài này thay bằng API thật của bài 6 và 7, và giải quyết những thứ làm giao diện nhà máy khó chịu nếu làm sơ sài: đang tải, lỗi, danh sách rỗng, bảng lớn, form nhập sai.
1. Vấn đề của useEffect + fetch thuần
useEffect(() => {
api("/assets").then(setAssets).catch(setError).finally(() => setLoading(false));
}, []);
Cách này chạy được nhưng thiếu rất nhiều: huỷ khi chuyển trang, tải lại khi quay lại tab, dùng chung dữ liệu giữa các màn hình, tự làm mới sau khi sửa. TanStack Query giải quyết các việc đó. Cài đặt:
npm install @tanstack/react-query
main.jsx:
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 30_000, retry: 1, refetchOnWindowFocus: true } },
});
// <QueryClientProvider client={queryClient}> bọc ngoài <AuthProvider>
2. Đọc dữ liệu với useQuery
Một "khoá truy vấn" (query key) định danh dữ liệu. Khi khoá đổi (ví dụ đổi trang), dữ liệu được tải lại.
src/features/assets/useAssets.js:
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { api } from "../../api.js";
export function useAssets({ q, page, pageSize }) {
const params = new URLSearchParams({ page, pageSize });
if (q) params.set("q", q);
return useQuery({
queryKey: ["assets", { q, page, pageSize }],
queryFn: () => api(`/assets?${params}`),
placeholderData: keepPreviousData, // giữ bảng cũ khi chuyển trang, không nhấp nháy
});
}
Kết quả của useQuery có data, isPending (lần đầu chưa có dữ liệu), isFetching (đang tải bất cứ lúc nào), error.
3. Bảng phân trang tìm kiếm
Hook chờ người dùng gõ xong (debounce)
Không nên gọi API ở mỗi phím gõ:
import { useEffect, useState } from "react";
export function useDebounced(value, delay = 300) {
const [v, setV] = useState(value);
useEffect(() => {
const id = setTimeout(() => setV(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return v;
}
Trang thiết bị
src/pages/Cmms.jsx (phần thiết bị):
import { useState } from "react";
import { useAssets } from "../features/assets/useAssets.js";
import { useDebounced } from "../hooks/useDebounced.js";
const STATUS = { 0: "Dừng", 1: "Chạy", 2: "Hỏng", 3: "Bảo trì" };
const PAGE_SIZE = 10;
export default function AssetsTable({ onEdit }) {
const [text, setText] = useState("");
const [page, setPage] = useState(1);
const q = useDebounced(text);
const { data, isPending, isFetching, error } = useAssets({ q, page, pageSize: PAGE_SIZE });
const totalPages = data ? Math.max(Math.ceil(data.total / PAGE_SIZE), 1) : 1;
return (
<section>
<input
value={text}
onChange={(e) => { setText(e.target.value); setPage(1); }} // đổi từ khoá thì về trang 1
placeholder="Tìm theo mã hoặc tên…"
/>
{isFetching && <span className="muted"> Đang tải…</span>}
{isPending && <p>Đang tải dữ liệu…</p>}
{error && <p role="alert">Không tải được: {error.message}</p>}
{data && (
<>
<table>
<thead>
<tr><th>Mã</th><th>Tên</th><th>Khu vực</th><th>Trạng thái</th><th /></tr>
</thead>
<tbody>
{data.items.map((a) => (
<tr key={a.id}>
<td>{a.code}</td>
<td>{a.name}</td>
<td>{a.line ?? "—"}</td>
<td><span className={`badge s${a.status}`}>{STATUS[a.status]}</span></td>
<td><button onClick={() => onEdit(a)}>Sửa</button></td>
</tr>
))}
{data.items.length === 0 && (
<tr><td colSpan={5}>Không có thiết bị phù hợp.</td></tr>
)}
</tbody>
</table>
<div className="pager">
<button disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>← Trước</button>
<span>Trang {page}/{totalPages} · {data.total} thiết bị</span>
<button disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Sau →</button>
</div>
</>
)}
</section>
);
}
Hãy luôn xử lý đủ ba trạng thái phụ: đang tải, lỗi, rỗng. Màn hình giám sát trắng tinh khi mạng chập chờn là điều trưởng ca ghét nhất.
4. Ghi dữ liệu với useMutation
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../../api.js";
export function useSaveAsset() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, input }) =>
id ? api(`/assets/${id}`, { method: "PUT", body: input })
: api("/assets", { method: "POST", body: input }),
onSuccess: () => qc.invalidateQueries({ queryKey: ["assets"] }), // làm mới mọi danh sách thiết bị
});
}
export function useDeleteAsset() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id) => api(`/assets/${id}`, { method: "DELETE" }),
onSuccess: () => qc.invalidateQueries({ queryKey: ["assets"] }),
});
}
invalidateQueries đánh dấu dữ liệu cũ và tải lại, nên bảng tự cập nhật sau khi lưu mà bạn không phải sửa state bằng tay.
5. Form có kiểm tra dữ liệu
Có thư viện (React Hook Form, Zod), nhưng hiểu cách làm tay giúp bạn dùng thư viện tốt hơn.
src/features/assets/AssetForm.jsx:
import { useState } from "react";
import { useSaveAsset } from "./useAssets.js";
const empty = { code: "", name: "", assetType: "Machine", line: "", status: 0, idealCycleSec: "" };
function validate(v) {
const e = {};
if (!v.code.trim()) e.code = "Nhập mã thiết bị";
else if (v.code.length > 30) e.code = "Tối đa 30 ký tự";
if (!v.name.trim()) e.name = "Nhập tên thiết bị";
if (v.idealCycleSec !== "" && !(Number(v.idealCycleSec) > 0)) e.idealCycleSec = "Phải là số dương";
return e;
}
export default function AssetForm({ asset, onDone }) {
const [v, setV] = useState(asset ? { ...empty, ...asset, line: asset.line ?? "", idealCycleSec: asset.idealCycleSec ?? "" } : empty);
const [errors, setErrors] = useState({});
const save = useSaveAsset();
const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
function submit(e) {
e.preventDefault();
const errs = validate(v);
setErrors(errs);
if (Object.keys(errs).length) return;
save.mutate(
{
id: asset?.id,
input: {
...v,
status: Number(v.status),
line: v.line || null,
idealCycleSec: v.idealCycleSec === "" ? null : Number(v.idealCycleSec),
},
},
{ onSuccess: onDone }
);
}
return (
<form onSubmit={submit} noValidate>
<label>Mã <input value={v.code} onChange={set("code")} /></label>
{errors.code && <small role="alert">{errors.code}</small>}
<label>Tên <input value={v.name} onChange={set("name")} /></label>
{errors.name && <small role="alert">{errors.name}</small>}
<label>Loại
<select value={v.assetType} onChange={set("assetType")}>
<option>Machine</option><option>Motor</option><option>Pump</option><option>Line</option>
</select>
</label>
<label>Khu vực <input value={v.line} onChange={set("line")} /></label>
<label>Trạng thái
<select value={v.status} onChange={set("status")}>
<option value={0}>Dừng</option><option value={1}>Chạy</option>
<option value={2}>Hỏng</option><option value={3}>Bảo trì</option>
</select>
</label>
<label>Chu kỳ chuẩn (giây) <input value={v.idealCycleSec} onChange={set("idealCycleSec")} inputMode="decimal" /></label>
{errors.idealCycleSec && <small role="alert">{errors.idealCycleSec}</small>}
{save.error && <p role="alert">{save.error.message}</p>}
<button disabled={save.isPending}>{save.isPending ? "Đang lưu…" : "Lưu"}</button>
<button type="button" onClick={onDone}>Huỷ</button>
</form>
);
}
Hai tầng kiểm tra cùng tồn tại: phía React (phản hồi nhanh) và phía C# (bắt buộc, vì không tin dữ liệu từ trình duyệt). Lỗi trùng mã (409) của máy chủ hiện ra qua save.error.message nhờ hàm api() đọc trường message.
Hộp thoại
Dùng <dialog> của HTML cho gọn:
import { useEffect, useRef } from "react";
export default function Modal({ open, onClose, title, children }) {
const ref = useRef(null);
useEffect(() => {
const d = ref.current;
if (open && !d.open) d.showModal();
if (!open && d.open) d.close();
}, [open]);
return (
<dialog ref={ref} onClose={onClose}>
<h3>{title}</h3>
{open && children}
</dialog>
);
}
Ghép trong trang thiết bị:
const [editing, setEditing] = useState(null); // null: đóng; {}: thêm mới; asset: sửa
<button onClick={() => setEditing({})}>+ Thêm thiết bị</button>
<AssetsTable onEdit={setEditing} />
<Modal open={editing !== null} onClose={() => setEditing(null)} title={editing?.id ? "Sửa thiết bị" : "Thêm thiết bị"}>
<AssetForm asset={editing?.id ? editing : null} onDone={() => setEditing(null)} />
</Modal>
{open && children} giúp form được tạo mới mỗi lần mở, nên trạng thái ô nhập luôn sạch.
6. Tổ chức mã theo tính năng
src/
├─ api.js
├─ auth/ AuthContext.jsx, RequireAuth.jsx
├─ hooks/ useDebounced.js
├─ components/ Modal.jsx, Pager.jsx, StatusBadge.jsx
├─ features/
│ ├─ assets/ useAssets.js, AssetForm.jsx, AssetsTable.jsx
│ ├─ maintenance/ (bài 9)
│ ├─ production/ (bài 10)
│ └─ inventory/ (bài 11)
└─ pages/ Cmms.jsx, Mes.jsx, Erp.jsx, Login.jsx
Gom mã theo tính năng (assets, maintenance...) thay vì theo loại tệp, để khi làm một phân hệ bạn chỉ cần mở một thư mục.
7. Khi nào dùng thư viện bảng, biểu đồ
- Bảng phức tạp (cột kéo thả, nhóm, xuất Excel): cân nhắc TanStack Table hoặc AG Grid. Bảng trong bài này đủ cho 80% màn hình quản trị.
- Biểu đồ: Recharts hoặc Chart.js. Bài 10 dùng Recharts cho dashboard OEE.
- Giao diện thành phần: có thể dùng Material UI, Ant Design hoặc Tailwind để tiết kiệm công viết CSS.
Bài tập
- Thêm nút Xoá (chỉ
Admin) có hộp xác nhận, dùnguseDeleteAsset, hiện thông báo 409 nếu thiết bị đã có dữ liệu liên quan. - Thêm bộ lọc theo trạng thái và theo khu vực, đưa vào khoá truy vấn và vào URL (
useSearchParams), để nhấn F5 vẫn giữ nguyên bộ lọc. - Thêm sắp xếp theo cột (bấm tiêu đề), gửi
sortlên API ở bài tập 2 của bài 6. - Làm ô thông báo (toast) hiện "Đã lưu" sau khi thêm hoặc sửa thành công.
Tóm tắt
- TanStack Query lo việc tải, lưu đệm, tải lại và đồng bộ dữ liệu;
useMutation+invalidateQueriesgiữ bảng luôn mới. - Luôn xử lý đang tải, lỗi, rỗng; phân trang và tìm kiếm ở máy chủ, có debounce.
- Kiểm tra dữ liệu hai tầng: React cho tiện, máy chủ cho an toàn.
- Gom mã theo tính năng.
- Ba bài tiếp theo xây ba phân hệ trên nền này: bài 9 CMMS.