Fetching
A request runs when you call send() on it. This guide sends a request, passes values to it, reads the response, picks
a cache policy, follows the lifecycle and aborts calls that are no longer needed.
- How to send a request and read the response object.
- How to pass params, query params and payload with setters or to
send(). - How to read the cache with
cachePolicyandread(). - How to follow the lifecycle and abort a request.
- The difference between
send()andexec().
Send a request
send() resolves with a response object for every outcome, including HTTP errors, timeouts and aborts. It never
rejects, so you branch on the result instead of using try/catch.
import { client } from "./client";
export const getUser = client.createRequest<{
response: { id: number; name: string };
}>()({
endpoint: "/users/:userId",
});
const { data, error, status } = await getUser.send({ params: { userId: 1 } });
if (data) {
console.log(data.name);
} else {
console.error(status, error);
}
Check data rather than success: data stays typed as nullable after if (success).
| Name | Type | Description |
|---|---|---|
| data | | Response data when successful, null on error |
| error | | Error payload when the request fails, null on success |
| extra | | Adapter-specific metadata (e.g., response headers) |
| requestTimestamp | | Timestamp (ms) when the request was sent |
| responseTimestamp | | Timestamp (ms) when the response was received |
| status | | HTTP status code or adapter-specific status indicator |
| success | | Whether the request completed successfully |
Pass params, query params and payload
Set values ahead of time with setters, or pass them to send(). Both are typed from the request's generics and its
endpoint. Setters return a new request, so use the returned value.
export const updateUser = client.createRequest<{
response: { id: number; name: string };
payload: { name: string };
queryParams?: { notify?: boolean };
}>()({ endpoint: "/users/:userId", method: "PUT" });
// Prepare it step by step
const prepared = updateUser
.setParams({ userId: 1 })
.setPayload({ name: "Ann" })
.setQueryParams({ notify: true });
await prepared.send();
// Or pass everything at once
await updateUser.send({
params: { userId: 1 },
payload: { name: "Ann" },
queryParams: { notify: true },
});
send() also accepts the other request options for one call, such as retry, headers or options. Each value has
its own guide: parameters, query params,
payload and headers.
Read from the cache
Plain send() is network-only: it writes a successful response to the cache but never reads it. Pick
another cachePolicy to read first, or call read() to get the cached response without a request.
cachePolicy | Returns |
|---|---|
"network-only" (default) | The network response |
"cache-first" | The cached response when there is one, fresh or stale, else the network response |
"revalidate" | The cached response at once, and refetches in the background |
const request = getUser.setParams({ userId: 1 });
const fast = await request.send({ cachePolicy: "cache-first" });
const cached = request.read(); // response or undefined, no network call
Neither policy looks at staleTime. Hooks in @hyper-fetch/react do, see
cache revalidation.
Follow the lifecycle
send() takes callbacks for one call. Each receives the requestId and the request.
await uploadFile.send({
payload: formData,
onBeforeSent: ({ requestId }) => console.log("queued", requestId),
onRequestStart: () => showSpinner(),
onUploadProgress: ({ progress, loaded, total }) =>
console.log(`${progress}% (${loaded}/${total})`),
onDownloadProgress: ({ progress }) => console.log(`download ${progress}%`),
onRetry: ({ retry, delay }) => console.log(`retry ${retry} in ${delay} ms`),
onResponse: ({ response }) => hideSpinner(response.success),
onRemove: () => console.log("removed from the queue"),
});
onBeforeSent is the earliest point with the requestId. To track every call of a request instead of one, register
listeners with request.$hooks, see Request lifecycle.
Abort a request
request.abort() aborts every in-flight request with the same abortKey. The send() promise resolves with an
AbortError in error. client.requestManager.abortByKey(abortKey) does the same from anywhere.
To abort the previous call automatically when a new one starts, see cancellation.
Send without queues or cache: exec()
exec() calls the adapter directly. Interceptors and mappers run, but there is no deduplication, queue, retry, offline
handling or cache write. Use it for one-off calls, for example on a server where each call is independent.
const { data, error } = await getUser.exec({ params: { userId: 1 } });
| Feature | send() | exec() |
|---|---|---|
| Interceptors, mappers, mocks | Yes | Yes |
| Deduplication, queues, retries, offline | Yes | No |
Cache write and cachePolicy | Yes | No |
Callbacks such as onResponse | Yes | No |
You've learned how to send requests with HyperFetch.
- You can send a request and branch on
dataanderror, withouttry/catch. - You can pass params, query params and payload with setters or to
send(). - You can read the cache with
cachePolicyorread(). - You can follow the lifecycle with callbacks and abort requests by
abortKey.
Runnable examples: Fetch on click, Vanilla TypeScript and Download progress.