useApi
Hook that returns a raw axios instance for calling APIs outside your app by absolute URL.
Usage
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 }))} />;
}Signature
app/hooks.ts
import type { AxiosInstance } from "axios";
function useApi(): AxiosInstance;Parameters
None.
Returns
An axios instance, created once per component. Every request:
- has your app’s API as
baseURL, so a relative path such as"/orders"goes to your own app; - sends
Authorization: Bearer <token>when a token is set (see setAuthToken), unless you set theAuthorizationheader yourself. The token goes only to the app’s own API (a relative URL or the API’s origin); outside URLs never receive it.
The instance also handles errors the same way on every page:
- A read (
GET,HEAD) that hits a network error, or a busy answer withretryable: true(429, 503, 504, see Error codes), is asked again, up to 3 attempts in all: it waits exactlyretry-after, or backs off with jitter when there is none. When the server asks for more than 8 seconds the error reaches the page at once. A 4xx other than 429 is never retried. - A write retries only with an
Idempotency-Keyheader (http.post(url, body, { headers: { "Idempotency-Key": key } })): without a key the first attempt may already have landed. - The last error carries
e.ftCode(the error code) ande.requestId(the request’s id, to find it in the logs). - A signed-in request that gets a 401 (expired session or locked account) signs the user out and goes to
/loginonce. - In apps framed by
AppShellfrommanh/shell, any other error shows the server’s message by itself. Pass{ silent: true }in a call’s config to turn that off.
The result is an AxiosResponse: the data is in res.data.
Examples
useApi is a real hook. Call it at the top of the component, keep the instance in a variable and use that instance in event handlers:
app/components/tax-lookup.tsx
const http = useApi();
async function lookup(taxCode: string) {
const res = await http.get(`https://api.example.vn/tax/${taxCode}`);
return res.data;
}- For your app’s own API, use useApiClient.
useApi()with a"/…"path still works but is untyped, andcheckwarnscode.no-raw-useapi-on-own-backend.
Next steps
- Call the API from the UI: how pages read and write data, end to end.
- useRequest: keep
dataandloadingwhen calling an outside API.
Last updated