Axios
A product list where axios performs the HTTP calls. The requests and the hook are the same as in any HyperFetch app; the adapter, the request options and the error type come from axios.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import { getProducts } from "./api";
export const App = () => {
const [delay, setDelay] = useState(500);
// A regular HyperFetch hook. Cache, retries and dedupe work the same; axios only sends the HTTP request.
const { data, error, loading, extra, status, refetch } = useFetch(
// `select` and `delay` are dummyjson query params: return only these fields, answer after `delay` ms.
getProducts.setQueryParams({ limit: 6, select: "title,price,thumbnail", delay }),
);
return (
<main className="container">
<hgroup>
<h1>Products</h1>
<p>
HyperFetch requests sent by axios. Raise the server delay above the 2s axios timeout to see an AxiosError.
</p>
</hgroup>
<article>
<label>
Server delay: {delay} ms {delay > 2000 && <mark>above the axios timeout</mark>}
<input
type="range"
min={0}
max={4000}
step={250}
value={delay}
onChange={(event) => setDelay(Number(event.target.value))}
/>
</label>
<div className="toolbar muted">
<span>
status {status ?? "-"} · content-type {String(extra?.headers["content-type"] ?? "-")}
</span>
<button type="button" className="outline secondary" onClick={refetch} disabled={loading}>
Reload
</button>
</div>
</article>
{loading && <progress />}
{error && (
<article>
<header>
<strong className="error">{error.name}</strong>
</header>
{/* The error is the AxiosError itself, with its code, config and response. */}
<p>
<code>{error.code}</code> {error.message}
</p>
<small className="muted">
{error.config?.method?.toUpperCase()} {error.config?.url}
</small>
</article>
)}
{!error && data && (
<div className="products">
{data.products.map((product) => (
<article key={product.id}>
<img src={product.thumbnail} alt="" width={64} height={64} />
<div>
<strong>{product.title}</strong>
<p className="muted">${product.price}</p>
</div>
</article>
))}
</div>
)}
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/axios hyper-fetch-react-axios && cd hyper-fetch-react-axios && npm install && npm run devsetAdapter(AxiosAdapter)makes axios the transport for every request of the client.- Axios options go in the request
options, typed as the axios request config. AxiosErroris the error type of the client, withcode,configandresponse.- Response headers from axios are in
extra.headers.
How it works
-
api.tscreates the client withcreateClient<{ error: AxiosError }>()and callssetAdapter(AxiosAdapter). The generic typeserrorin every hook andsend()result. -
getProductssets axios options inoptions. They are passed to theaxios()call as they are:options: {timeout: 2000,transitional: { clarifyTimeoutError: true },},The adapter owns
url,baseURL,method,data,signaland the progress callbacks, so those are left out of the type. -
AppcallsuseFetchwith adelayquery param. DummyJSON waits that long before it answers. -
When the delay goes over 2 seconds, axios aborts the request. The response resolves with
success: falseand theAxiosErroraserror, with theETIMEDOUTcode fromclarifyTimeoutErrorand the requestconfig. -
On success,
extra.headersholds the axios response headers, andstatusthe HTTP status.
- Projects that already configure axios and want HyperFetch caching, queues and hooks on top.
- Code that relies on axios features such as its timeout handling,
validateStatusortransformResponse. - Node.js environments where you prefer axios over
fetch.
Related
One setAdapter(AxiosAdapter) call moves the client to axios. Axios options go in options, and failures arrive as a
typed AxiosError in the response.
