Skip to main content

Refetch on focus

A random todo that is fetched again when you come back to the tab, leave it, or get your connection back. Each option has a switch, and a log prints every focus or network event followed by the request it caused.

intermediateuseFetchoffline
import { useAppManager, useFetch } from "@hyper-fetch/react";
import { useEffect, useState } from "react";

import { client, getRandomTodo } from "./api";

type LogEntry = { id: number; time: string; text: string; kind: "event" | "request" };
let nextId = 0;

type Options = { refetchOnFocus: boolean; refetchOnBlur: boolean; refetchOnReconnect: boolean };
const optionNames: (keyof Options)[] = ["refetchOnFocus", "refetchOnBlur", "refetchOnReconnect"];

export const App = () => {
const [options, setOptions] = useState<Options>({
refetchOnFocus: true,
refetchOnBlur: false,
refetchOnReconnect: true,
});
const [log, setLog] = useState<LogEntry[]>([]);
const { isFocused, isOnline, setFocused, setOnline } = useAppManager(client);

const { data, error, loading, onRequestStart } = useFetch(getRandomTodo, options);

const addLog = (text: string, kind: LogEntry["kind"]) => {
const entry = { id: nextId++, time: new Date().toLocaleTimeString(), text, kind };
setLog((entries) => [entry, ...entries].slice(0, 12));
};

// The cause: focus and network events of the app manager.
useEffect(() => {
const unmount = [
client.appManager.events.onFocus(() => addLog("focus", "event")),
client.appManager.events.onBlur(() => addLog("blur", "event")),
client.appManager.events.onOnline(() => addLog("online", "event")),
client.appManager.events.onOffline(() => addLog("offline", "event")),
];
return () => unmount.forEach((callback) => callback());
}, []);

// The effect: every request this hook sends.
onRequestStart(() => addLog("GET /todos/random", "request"));

return (
<main className="container">
<hgroup>
<h1>Refetch on focus</h1>
<p>Switch to another tab or window and come back. The log shows each event and the request it caused.</p>
</hgroup>

<div className="grid-2">
<section>
<fieldset>
{optionNames.map((name) => (
<label key={name}>
<input
type="checkbox"
role="switch"
checked={options[name]}
onChange={(event) => setOptions((current) => ({ ...current, [name]: event.target.checked }))}
/>
<code>{name}</code>
</label>
))}
</fieldset>

<p>
Window <mark>{isFocused ? "focused" : "blurred"}</mark> · Network{" "}
<mark>{isOnline ? "online" : "offline"}</mark>
</p>
{/* Leaving the tab is easy, losing the network is not. These buttons send the same app manager events. */}
<div className="buttons">
<button type="button" className="outline secondary" onClick={() => setFocused(!isFocused)}>
Simulate {isFocused ? "blur" : "focus"}
</button>
<button type="button" className="outline secondary" onClick={() => setOnline(!isOnline)}>
Go {isOnline ? "offline" : "online"}
</button>
</div>

{error && <article>Could not load a todo: {error.message}</article>}
{!data && loading && <article aria-busy="true">Loading...</article>}
{data && (
<article aria-busy={loading}>
{data.completed ? "✓" : "○"} {data.todo}
</article>
)}
</section>

<article>
<header>
<strong>Log</strong>
</header>
<ul className="log">
{log.map((entry) => (
<li key={entry.id} className={entry.kind}>
<small className="muted">{entry.time}</small> {entry.kind === "request" ? "→ " : ""}
{entry.text}
</li>
))}
</ul>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/refetch-on-focus hyper-fetch-react-refetch-on-focus && cd hyper-fetch-react-refetch-on-focus && npm install && npm run dev
What it shows
  1. refetchOnFocus refetches when the window or tab gets focus again.
  2. refetchOnBlur refetches when the user leaves the window or tab.
  3. refetchOnReconnect refetches when the network comes back.
  4. The app manager (client.appManager) is the source of these events, and useAppManager reads and sets its state.

How it works​

  1. App keeps the three options in state and passes them straight to useFetch(getRandomTodo, options). The hook reads the current value when an event arrives, so the switches take effect at once.
  2. The client's app manager listens to the browser's visibilitychange, focus, blur, online and offline events and emits focus, blur, online and offline. The hook refetches on the events its options allow.
  3. A useEffect subscribes to client.appManager.events to log the cause, and the hook's onRequestStart callback logs the request that follows it.
  4. useAppManager(client) returns isFocused and isOnline for the status line, plus setFocused and setOnline. The "Simulate" and "Go offline" buttons call them, which emits the same events as the browser would. That makes reconnects easy to try without unplugging anything.
  5. Switching tabs can fire both visibilitychange and focus, so the log may show two focus events. Deduplication of GET requests still sends only one request.
const { data } = useFetch(getRandomTodo, {
refetchOnFocus: true,
refetchOnBlur: false,
refetchOnReconnect: true,
});

All three options are false by default. Each refetch also restarts the refreshTime timer when polling is on.

When to use it
  • Data that other people or other tabs change, such as inboxes, carts or shared boards.
  • Apps used on phones, where users switch apps and lose the network often.

Summary

You refetched data on focus, blur and reconnect with three useFetch options, logged each app manager event next to the request it caused, and simulated the events with useAppManager.