Skip to main content
Version: v10.5.0

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.

What you'll learn
  1. How to send a request and read the response object.
  2. How to pass params, query params and payload with setters or to send().
  3. How to read the cache with cachePolicy and read().
  4. How to follow the lifecycle and abort a request.
  5. The difference between send() and exec().

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.

src/api/users.ts
import { client } from "./client";

export const getUser = client.createRequest<{
response: { id: number; name: string };
}>()({
endpoint: "/users/:userId",
});
src/app.ts
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).

ResponseType
Name Type Description
data
GenericDataType | null
Response data when successful, null on error
error
GenericErrorType | null
Error payload when the request fails, null on success
extra
ExtractAdapterExtraType<Adapter> | null
Adapter-specific metadata (e.g., response headers)
requestTimestamp
number
Timestamp (ms) when the request was sent
responseTimestamp
number
Timestamp (ms) when the response was received
status
ExtractAdapterStatusType<Adapter> | null
HTTP status code or adapter-specific status indicator
success
boolean
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.

src/api/users.ts
export const updateUser = client.createRequest<{
response: { id: number; name: string };
payload: { name: string };
queryParams?: { notify?: boolean };
}>()({ endpoint: "/users/:userId", method: "PUT" });
src/app.ts
// 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.

cachePolicyReturns
"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
src/app.ts
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.

src/upload.ts
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.

Live results

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.

Live results

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.

server/report.ts
const { data, error } = await getUser.exec({ params: { userId: 1 } });
Featuresend()exec()
Interceptors, mappers, mocksYesYes
Deduplication, queues, retries, offlineYesNo
Cache write and cachePolicyYesNo
Callbacks such as onResponseYesNo

Congratulations!

You've learned how to send requests with HyperFetch.

  • You can send a request and branch on data and error, without try/catch.
  • You can pass params, query params and payload with setters or to send().
  • You can read the cache with cachePolicy or read().
  • You can follow the lifecycle with callbacks and abort requests by abortKey.

Runnable examples: Fetch on click, Vanilla TypeScript and Download progress.

Request
Options, keys and methods of a request.
Error handling
Read and type the errors a request returns.
Request API reference
Every method of the Request class with its signature.