Polling
A quote card that asks the server for a new random quote every few seconds. Switches turn polling on and off and decide whether it continues in a background tab, and a progress bar shows when the next refresh is due.
beginneruseFetchpolling
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 { useEffect, useState } from "react";
import { getRandomQuote } from "./api";
const intervals = [2000, 5000, 10000];
/** Re-renders every 250 ms, only to show how long ago the data arrived. */
const useNow = () => {
const [now, setNow] = useState(Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 250);
return () => clearInterval(id);
}, []);
return now;
};
export const App = () => {
const [polling, setPolling] = useState(true);
const [refreshTime, setRefreshTime] = useState(5000);
const [inBackground, setInBackground] = useState(false);
const [updates, setUpdates] = useState(0);
const now = useNow();
const { data, error, loading, responseTimestamp, refetch, onSuccess } = useFetch(getRandomQuote, {
// `refresh` turns polling on, `refreshTime` is the interval in ms.
refresh: polling,
refreshTime,
// `false` pauses polling while the tab is hidden or the window is not focused.
refetchBlurred: inBackground,
});
onSuccess(() => setUpdates((count) => count + 1));
const elapsed = responseTimestamp ? now - responseTimestamp.getTime() : 0;
return (
<main className="container">
<hgroup>
<h1>Polling</h1>
<p>A new random quote is requested every few seconds while polling is on.</p>
</hgroup>
<fieldset className="controls">
<label>
<input
type="checkbox"
role="switch"
checked={polling}
onChange={(event) => setPolling(event.target.checked)}
/>
Polling
</label>
<label>
<input
type="checkbox"
role="switch"
checked={inBackground}
onChange={(event) => setInBackground(event.target.checked)}
/>
Keep polling in a background tab
</label>
<div role="group">
{intervals.map((value) => (
<button
key={value}
type="button"
className={value === refreshTime ? undefined : "outline secondary"}
onClick={() => setRefreshTime(value)}
>
Every {value / 1000}s
</button>
))}
</div>
</fieldset>
{error && <article>Could not load a quote: {error.message}</article>}
{!data && loading && <article aria-busy="true">Loading...</article>}
{data && (
<article>
<blockquote>
{data.quote}
<footer>
<cite>{data.author}</cite>
</footer>
</blockquote>
<footer className="status">
<small className="muted">
Last updated {responseTimestamp?.toLocaleTimeString()} ({Math.floor(elapsed / 1000)}s ago) · Responses
received: {updates}
</small>
<button type="button" className="outline secondary" onClick={refetch} aria-busy={loading}>
Refresh now
</button>
</footer>
{polling && <progress value={Math.min(elapsed, refreshTime)} max={refreshTime} aria-label="Next refresh" />}
</article>
)}
</main>
);
};
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/polling hyper-fetch-react-polling && cd hyper-fetch-react-polling && npm install && npm run devWhat it shows
refreshturns polling on and off for oneuseFetchcall.refreshTimesets the interval in milliseconds and can change while the component is mounted.refetchBlurreddecides whether polling continues while the tab is hidden or the window is not focused.refetch()fetches right away and starts the interval over.
How it works
api.tsdefinesgetRandomQuotefor dummyjson/quotes/random, which returns a different quote on every call.Apppasses{ refresh: polling, refreshTime, refetchBlurred: inBackground }touseFetch. All three come from React state, so the controls change them without remounting anything.- After each refresh the hook starts a new
refreshTimetimer. A refresh is skipped while a request for the same data is still running, so a slow server never gets overlapping polls. - With
refetchBlurred: false(the switch off) the timer keeps running in a background tab but sends nothing. Polling continues when you come back. The hook default istrue. responseTimestampis the time of the last response. A smalluseNowclock re-renders four times a second to show how long ago that was and to fill the progress bar.onSuccesscounts the responses, and "Refresh now" callsrefetch().
const { data, responseTimestamp, refetch } = useFetch(getRandomQuote, {
refresh: polling,
refreshTime,
refetchBlurred: inBackground,
});
When to use it
- Dashboards, job status pages and feeds where the server cannot push updates.
- Short intervals only while a screen is visible. For server pushes, see the realtime examples.
Related
Summary
You polled an endpoint with refresh and refreshTime, paused polling in background tabs with refetchBlurred, and
showed the time of the last update from responseTimestamp.
