Skip to main content

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.

beginneruseFetchsend
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>
);
};
Run locallynpx 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 dev
What it shows
  1. useFetch with disabled: the hook is mounted, but holds the request until a state flag allows it.
  2. request.send(): an imperative call from an event handler that resolves with the response.
  3. The difference: the hook owns data, loading, refreshing and the cache link; send() gives you one response to handle yourself.

How it works​

  1. Comments keeps a requested flag and passes it to the hook:

    const [requested, setRequested] = useState(false);
    const { data, error, loading, refetch } = useFetch(getPostCommentsRequest, { disabled: !requested });

    While disabled is true, useFetch sends nothing. When the flag flips, the hook fetches, and from then on it behaves like any useFetch: refetch() works, other options such as refetchOnFocus apply, and the data is read from and written to the cache.

  2. QuoteButton calls getRandomQuoteRequest.send() in the click handler. send() resolves with data, error, status and success, and it does not throw for a failed request, so there is no try/catch. The component keeps loading and the result in its own state.

  3. A response from send() is also saved in the cache, so a useFetch with the same request elsewhere would show it.

  4. RequestLog subscribes to client.requestManager.events.onRequestStart and shows that the page loads with zero requests.

When to use it
  • 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.

Summary

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.