Skip to Content

Call the API from the UI

≈ 10 min · you will have a React page that reads and writes data through the generated useApiClient() client and the useRequest hook, with reloads and error messages.

A .tsx page runs in the browser and can’t import server code. Every read and write (listing orders, changing one order’s status) goes over HTTP through a typed client manh.run generates from your handler files.

1. Get the client

useApiClient() from app/api returns a client with one function per handler. Each function returns exactly what the handler returned, with no .data.

app/orders/page.tsx
import { useApiClient } from "app/api"; export default function OrdersPage() { const api = useApiClient(); // api.orders.list({ page: 1, pageSize: 20 }) → { data, total } // … }

Function names come from the file path:

  • 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) · patch.ts or put.ts → api.orders.update(id, body) · delete.ts → api.orders.remove(id)
  • Sub-paths use their last segment: app/auth/login/post.ts → api.auth.login(body); app/orders/[id:int]/status/post.ts → api.orders.status(id, body)
  • Dashed folders become camelCase: app/chat-messages/get.ts → api.chatMessages.list()

2. Read data with useRequest

useRequest from app/hooks calls the function when the component mounts and returns { data, loading, error, run, refresh, mutate }.

app/orders/[id]/page.tsx
import { useParams } from "react-router-dom"; import { Card, Skeleton } from "antd"; import { useApiClient } from "app/api"; import { useRequest } from "app/hooks"; export default function OrderPage() { const { id } = useParams(); const api = useApiClient(); const { data, loading } = useRequest(() => api.orders.detail(Number(id)), { refreshDeps: [id], // reload when id changes }); if (loading) return <Skeleton active />; return <Card title={`Order ${data?.id}`}>{data?.customerName}</Card>; }

The options are manual, defaultData, refreshDeps, onSuccess and onError. There is no pollingInterval, debounceWait or cacheKey.

3. Write data with useAction

useAction(fn, { ok, reload }) from app/hooks wraps one write. It calls the API, shows ok or the server’s error message, reloads, then resolves true or false.

app/orders/[id]/page.tsx
const api = useApiClient(); const { data, refresh } = useRequest(() => api.orders.detail(Number(id)), { refreshDeps: [id] }); const markPaid = useAction(() => api.orders.update(Number(id), { status: "paid" }), { ok: "Payment recorded", reload: refresh }); <Button disabled={data?.status !== "pending"} onClick={() => markPaid()}>Mark as paid</Button>
  • In a modal form: onFinish={(v) => save(row.id, v)}. The form closes only when the write succeeds.
  • For buttons that move an order along its lifecycle, use FlowActions (see Build a CRUD feature).
  • To stop useRequest from running on mount, pass manual: true and call run().

4. List pages with ResourceList

A list page repeats the same work: load a page of data, search, filter by status, a create form. ResourceList from manh/shell does that work for one resource.

app/orders/page.tsx
import { ResourceList } from "manh/shell"; import { useApiClient } from "app/api"; import { OrderStatus } from "app/shared/order"; export default function OrdersPage() { const api = useApiClient(); return ( <ResourceList api={api.orders} title="Orders" path="/orders" status="status" statusEnum={OrderStatus} columns={[ { title: "Customer", dataIndex: "customerName", formItemProps: { rules: [{ required: true }] } }, { title: "Total", dataIndex: "total", valueType: "vnd" }, { title: "Status", dataIndex: "status", hideInForm: true }, ]} /> ); }
  • Each column is both a table column and a field of the Add form. The first column links to /orders/<id>.
  • Status tabs show counts when the list handler returns counts (listOf(…, { counts: "status" })).
  • rowActions(row, reload) adds buttons per row, toolBar(reload) adds buttons to the toolbar.
  • For a table of your own, use <ProTable request={tableRequest(api.orders.list)} /> with tableRequest from app/hooks.

The list handler receives these parameters through listSchema (see Build a CRUD feature).

5. Handle errors

When the server stops a request with fail(...), the promise rejects with the body { error, message, code }. Apps on AppShell show the server’s message by themselves when a call fails, so pages need no try / catch with message.error.

  • A 401 means the session expired or the account was locked. The app signs the user out and sends them to /login.
  • To show the error text somewhere else, such as inside a form: errorText(e) from manh/shell.

6. Call a third-party API

For APIs outside your app (maps, tax-code lookup), use useApi() from app/hooks: a raw axios instance. Use absolute URLs and read res.data yourself.

app/components/province-select.tsx
import { Select } from "antd"; import { useApi, useRequest } from "app/hooks"; export function ProvinceSelect(props: { value?: string; onChange?: (v: string) => void }) { const http = useApi(); // a hook: call it at the top of the component const { data, loading } = useRequest(() => http.get("https://provinces.example.vn/api/p/").then((r) => r.data), ); return <Select {...props} loading={loading} options={(data ?? []).map((p: any) => ({ label: p.name, value: p.code }))} />; }

For your own app’s API, use useApiClient() instead of useApi(). useApi() still works but has no types, and check warns code.no-raw-useapi-on-own-backend.

Good to know

  • Don’t import useRequest from ahooks, because the package isn’t on the allowlist.
  • To reload on a timer, call setInterval(refresh, ms) in a useEffect. To debounce typing, debounce the input value and pass it in refreshDeps.
  • After signIn(await api.auth.login(values)), every call through useApiClient() and useApi() sends Authorization: Bearer <token>. Don’t add the header or write to localStorage yourself.
  • List handlers return { data, total }; detail, create and update handlers return the record.
  • check reports a call to a function name the client doesn’t have.

Next steps

Last updated