Skip to Content

useAction

Hook bọc một lệnh ghi hay một thao tác từ giao diện: gọi API, báo kết quả, tải lại bảng và trả true hoặc false.

Form tạo và sửa dùng submit. Mọi nút và form khác (duyệt, đổi trạng thái, gửi lại, xoá, nhập file…) dùng useAction. Trang danh sách viết bằng <ResourceList> của manh/shell đã có sẵn các nút này, xem Trang danh sách.

Cách dùng

app/orders/page.tsx
import { useRef } from "react"; import { ProTable, ModalForm, ProFormSelect, type ActionType } from "@ant-design/pro-components"; import { useApiClient } from "app/api"; import { useAction, tableRequest } from "app/hooks"; import { OrderStatus } from "app/shared/order"; export default function OrdersPage() { const api = useApiClient(); const ref = useRef<ActionType>(); const move = useAction(api.orders.status, { ok: "Đã cập nhật", reload: ref }); return ( <ProTable rowKey="id" actionRef={ref} request={tableRequest(api.orders.list)} columns={[ { title: "Trạng thái", dataIndex: "status", valueEnum: OrderStatus.valueEnum }, { title: "Thao tác", valueType: "option", render: (_, row) => [ <ModalForm key="move" title="Đổi trạng thái" trigger={<a>Đổi trạng thái</a>} onFinish={(v) => move(row.id, v)}> <ProFormSelect name="to" label="Sang" options={OrderStatus.options} rules={[{ required: true }]} /> </ModalForm>, ] }, ]} /> ); }

Chữ ký

app/hooks.ts
function useAction<A extends any[]>( fn: (...args: A) => Promise<any>, opts?: string | { ok?: string; failed?: string; reload?: { current?: any } | (() => void) }, ): (...args: A) => Promise<boolean>;

Tham số

  • fn: hàm gọi API, thường là một hàm của useApiClient như api.orders.status.
  • opts: một chuỗi (chính là ok) hoặc một object:
    • ok: chữ báo khi thành công, mặc định “Đã lưu”. Chuỗi rỗng "" thì không báo.
    • failed: chữ báo khi lỗi mà server không gửi message, mặc định “Có lỗi xảy ra”.
    • reload: thứ cần tải lại sau khi thành công. Truyền actionRef của ProTable hoặc một hàm như refresh của useRequest.

Trả về

Một hàm nhận đúng các tham số của fn. Khi gọi, hàm chạy fn, hiện ok, tải lại thứ trong reload rồi trả true. Khi lỗi, hàm hiện message của server (hoặc failed) và trả false, không ném lỗi. App dùng khung AppShell của manh/shell đã tự hiện lỗi của API, nên useAction không hiện thêm lần thứ hai.

onFinish của ModalForm và DrawerForm cần đúng giá trị này: form chỉ đóng khi thao tác thành công.

Ví dụ

Một nút, tải lại trang chi tiết bằng refresh:

app/orders/[id]/page.tsx
const { data: order, refresh } = useRequest(() => api.orders.detail(id), { refreshDeps: [id] }); const approve = useAction(api.orders.approve, { ok: "Đã duyệt đơn", reload: refresh }); <Button type="primary" onClick={() => approve(id, {})}>Duyệt</Button>

Không tự viết try { await api…; message.success(); reload() } catch { message.error(…) }: useAction đã làm phần đó.

Bước tiếp theo

Cập nhật