Fetch on click
A page that sends no request when it opens. The left card loads comments when you click Show comments, the right card fetches a quote on every click. The log at the bottom lists each request the moment it starts. This is what other libraries call a lazy query.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useEffect, useState } from "react";
import { client } from "./api";
/** Lists every request the client sends, to prove that nothing goes out before you click. */
export const RequestLog = () => {
const [lines, setLines] = useState<string[]>([]);
useEffect(
() =>
client.requestManager.events.onRequestStart(({ request }) => {
const line = `${new Date().toLocaleTimeString()} GET ${request.endpoint}`;
setLines((current) => [line, ...current].slice(0, 6));
}),
[],
);
return (
<article>
<header>
<strong>Requests sent</strong>
</header>
{lines.length === 0 ? (
<p className="muted">None yet. The page loaded without a single request.</p>
) : (
<ol className="log">
{lines.map((line, index) => (
<li key={`${index}-${line}`}>{line}</li>
))}
</ol>
)}
</article>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/fetch-on-click hyper-fetch-react-fetch-on-click && cd hyper-fetch-react-fetch-on-click && npm install && npm run devuseFetchwithdisabled: the hook is mounted, but holds the request until a state flag allows it.request.send(): an imperative call from an event handler that resolves with the response.- The difference: the hook owns
data,loading, refreshing and the cache link;send()gives you one response to handle yourself.
How it works
-
Commentskeeps arequestedflag and passes it to the hook:const [requested, setRequested] = useState(false);const { data, error, loading, refetch } = useFetch(getPostCommentsRequest, { disabled: !requested });While
disabledistrue,useFetchsends nothing. When the flag flips, the hook fetches, and from then on it behaves like anyuseFetch:refetch()works, other options such asrefetchOnFocusapply, and the data is read from and written to the cache. -
QuoteButtoncallsgetRandomQuoteRequest.send()in the click handler.send()resolves withdata,error,statusandsuccess, and it does not throw for a failed request, so there is notry/catch. The component keepsloadingand the result in its own state. -
A response from
send()is also saved in the cache, so auseFetchwith the same request elsewhere would show it. -
RequestLogsubscribes toclient.requestManager.events.onRequestStartand shows that the page loads with zero requests.
disabled: data that is shown on screen but expensive or rarely needed, such as comments, details or a report. Also for requests that wait for input, like a search that needs a term first.send(): one-off actions whose result you use once, such as checking availability, exporting a file or prefetching before navigation.
Related
Use useFetch with disabled when the result belongs on screen and should stay fresh, and request.send() when a
handler needs one response. Both send nothing until the user asks.
