Skip to Content

useAction

Hook that wraps a write or any other action from the UI: it calls the API, shows the result, reloads the table and resolves true or false.

Create and edit forms use submit. Every other button and form (approve, change status, resend, delete, import…) uses useAction. A list page built with <ResourceList> from manh/shell already has these buttons, see List pages.

Usage

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: "Status updated", reload: ref }); return ( <ProTable rowKey="id" actionRef={ref} request={tableRequest(api.orders.list)} columns={[ { title: "Status", dataIndex: "status", valueEnum: OrderStatus.valueEnum }, { title: "Actions", valueType: "option", render: (_, row) => [ <ModalForm key="move" title="Change status" trigger={<a>Change status</a>} onFinish={(v) => move(row.id, v)}> <ProFormSelect name="to" label="To" options={OrderStatus.options} rules={[{ required: true }]} /> </ModalForm>, ] }, ]} /> ); }

Signature

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>;

Parameters

  • fn: the function that calls the API, usually a function of useApiClient such as api.orders.status.
  • opts: a string (used as ok) or an object:
    • ok: the success message, “Đã lưu” by default. An empty string "" shows nothing.
    • failed: the message when an error comes without a server message, “Có lỗi xảy ra” by default.
    • reload: what to reload after success. Pass the ProTable’s actionRef or a function such as refresh from useRequest.

Returns

A function that takes the same arguments as fn. When called, it runs fn, shows ok, reloads what reload points to and resolves true. On error it shows the server’s message (or failed) and resolves false; it doesn’t throw. Apps framed by AppShell from manh/shell already show API errors, so useAction never shows a second one.

That is what onFinish of ModalForm and DrawerForm expects: the form closes only when the action succeeded.

Examples

A single button that reloads a detail page with refresh:

app/orders/[id]/page.tsx
const { data: order, refresh } = useRequest(() => api.orders.detail(id), { refreshDeps: [id] }); const approve = useAction(api.orders.approve, { ok: "Order approved", reload: refresh }); <Button type="primary" onClick={() => approve(id, {})}>Approve</Button>

Don’t hand-write try { await api…; message.success(); reload() } catch { message.error(…) }: useAction does that.

Next steps

Last updated