Skip to main content

Data Fetching

Quy ước lấy dữ liệu từ API/backend trong ứng dụng Next.js. Hooks thuộc tầng client: gọi API hoặc Server Action, không gọi Prisma/Services trực tiếp (xem Kiến trúc & các tầng).

Custom hook với SWR​

Custom hook dùng để fetch, cache và revalidate dữ liệu phía client nên dùng SWR (hoặc quy định tương đương của dự án).

import useSWR from "swr";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export function useCustomers(params?: CustomerParams) {
const query = params ? new URLSearchParams(params).toString() : "";
const { data, error, mutate } = useSWR<Customer[]>(
`/api/customers${query ? `?${query}` : ""}`,
fetcher,
);
return {
customers: data,
isLoading: !error && !data,
isError: error,
mutate,
};
}

Lợi ích SWR: cache, revalidate on focus, retry, tránh fetch trùng, dùng được với Server Component (preload) và Client Component.

Export custom hook qua barrel (index.ts)​

Custom hook (ví dụ: useCustomers, useVehicles) phải export qua file index.ts trong thư mục hooks. Khi import ở nơi khác, luôn import từ barrel (@/hooks), không import trực tiếp từ file riêng lẻ từng hook (trừ khi team quy định khác).

Ví dụ cấu trúc thư mục:

src/
├── hooks/
│ ├── useCustomers.ts
│ ├── useVehicles.ts
│ └── index.ts

index.ts:

// hooks/index.ts
export { default as useContainerTypeOptions } from "./useContainerTypeOptions";
export { default as useContainerTypes } from "./useContainerTypes";
export { default as useCustomer } from "./useCustomer";

Cách import đúng ở component hoặc page:

import { useCustomers, useContainerTypes } from "@/hooks";

Tránh cách import sau (KHÔNG nên):

import useCustomers from "@/hooks/useCustomers";

Lợi ích:

  • Thay đổi/tổ chức lại tên file chỉ cần cập nhật index.ts.
  • Import gọn, tập trung, dễ refactor.
  • Đảm bảo đồng bộ khi mở rộng số lượng hook.

Tham khảo thêm: TypeScript - Modules (import path, barrel export).