Skip to Content

useApiClient

Hook trả client có kiểu cho API của chính app, sinh từ các file handler. Mỗi hàm trả đúng giá trị handler đã trả.

Cách dùng

app/orders/[id]/page.tsx
import { useParams } from "react-router-dom"; import { useApiClient } from "app/api"; import { useRequest } from "app/hooks"; export default function OrderPage() { const { id } = useParams(); const api = useApiClient(); const { data: order } = useRequest(() => api.orders.detail(Number(id)), { refreshDeps: [id] }); return <h1>Đơn {order?.id}</h1>; }

useApiClient là hook: gọi ở đầu component, không gọi trong hàm xử lý sự kiện hay vòng lặp.

Chữ ký

app/api.ts
export type ApiClient = ReturnType<typeof buildClient>; export function useApiClient(): ApiClient;

app/api.ts do manh.run sinh lại mỗi lần build. Không sửa file này.

Tham số

Không có.

Trả về

Một object có một hàm cho mỗi file handler. Tên hàm lấy từ đường dẫn file:

  • app/orders/get.ts → api.orders.list(params?)
  • app/orders/post.ts → api.orders.create(body)
  • app/orders/[id:int]/get.ts → api.orders.detail(id)
  • app/orders/[id:int]/patch.ts hoặc put.ts → api.orders.update(id, body)
  • app/orders/[id:int]/delete.ts → api.orders.remove(id)
  • app/orders/[id:int]/approve/post.ts → api.orders.approve(id, body)
  • app/classes/[id:int]/attendance-export/get.ts có khai schema = { query } → api.classes.attendanceExport(id, params?)
  • app/reports/sales/get.ts → api.reports.sales(params?)
  • Mỗi thư mục tĩnh sau tài nguyên là một nhóm, tham số đường dẫn thành đối số theo thứ tự: app/courses/[id:int]/assistants/[instructorId:int]/delete.ts → api.courses.assistants.remove(id, instructorId). Có thêm app/courses/[id:int]/assistants/post.ts thì hàm đó vào cùng nhóm: api.courses.assistants.post(id, body)
  • Thư mục có gạch nối thành camelCase: app/chat-messages/get.ts → api.chatMessages.list()
  • put, patch, delete không có id giữ tên phương thức: app/settings/put.ts → api.settings.put(body)
  • Một thư mục con có nhiều handler thì thành một nhóm, mỗi handler mang tên CRUD bên trong: app/me/prefs/get.ts + app/me/prefs/patch.ts → api.me.prefs.list() + api.me.prefs.patch(body)
  • Hai handler vẫn trùng một tên ([id:int]/put.ts + [id:int]/patch.ts) thì check báo lỗi code.api-name-collision, nêu cả hai file. Giữ một file, hoặc chuyển một file vào thư mục con riêng (app/orders/[id:int]/reprice/patch.ts → api.orders.reprice(id, body)).

Tham số đường dẫn nhận string | number. Hàm GET và DELETE không có id nhận params (query string); có id thì nhận params sau id khi handler khai query trong schema; POST, PUT, PATCH nhận body. Mọi hàm ghi (POST, PUT, PATCH, DELETE) nhận thêm đối số cuối tuỳ chọn opts?: ApiCallOptions, hiện chỉ có idempotencyKey.

Mỗi hàm trả Promise của đúng giá trị handler trả: handler danh sách trả { data, total }, handler chi tiết, tạo, sửa trả bản ghi. Không thêm .data.

Khi server trả lỗi, promise bị từ chối với lỗi của axios; body lỗi nằm ở e.response.data dạng { error, message, code }. Lỗi bận của manh.run có thêm retryable, retryAfterSeconds, requestId (xem Mã lỗi).

Ví dụ

Đưa client vào ProTable tự viết:

app/orders/page.tsx
<ProTable<Order> rowKey="id" columns={orderColumns} request={tableRequest(api.orders.list)} />

tableRequest đổi trang, sắp xếp, lọc và ô tìm của bảng thành query của API danh sách.

  • Sau signIn, mọi lệnh gọi tự gửi Authorization: Bearer <token>. Không tự thêm header.
  • Gọi tên hàm không có trong client thì check báo lỗi. Đọc app/api.ts để xem tên thật.
  • Client chạy trên cùng instance axios với useApi, nên lần đọc gặp lỗi bận cũng tự gọi lại và phiên hết hạn cũng đưa về /login.
  • Lệnh ghi chỉ tự gọi lại khi có idempotencyKey. Giữ một khoá cho một lần gửi (kể cả khi người dùng bấm lại vì mạng chậm), đổi khoá khi đã gửi xong:
app/orders/order-form.tsx
const key = useRef(crypto.randomUUID()); await api.orders.create(values, { idempotencyKey: key.current }); key.current = crypto.randomUUID(); // gửi xong: lần sau là đơn mới

Khoá đi tới handler ở header Idempotency-Key. Handler muốn chắc chắn không ghi trùng thì lưu khoá cùng bản ghi (cột unique) và trả lại bản ghi cũ khi gặp lại khoá.

Bước tiếp theo

  • API handler: handler trả gì thì client nhận nấy.
  • useRequest: gọi client khi trang mở và giữ data, loading.
  • submit: gửi form qua client.
Cập nhật