Skip to main content

Offline queue

A todo form that keeps working without a network. Todos added offline wait in the dispatcher queue and reach the server, in order, once the app is online again.

intermediateofflineuseQueuesend
import { useAppManager, useQueue } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";

import { addTodo, client, type Todo } from "./api";

type Saved = Todo & { savedAt: string };

const Queue = () => {
const { isOnline } = useAppManager(client);
// Reads the dispatcher queue of `addTodo` and updates on every change.
const { requests } = useQueue(addTodo);

return (
<article>
<h6>Queue ({requests.length})</h6>
{requests.length === 0 && <p className="muted">Empty. Every todo has reached the server.</p>}
<ol className="list">
{requests.map((item) => (
<li key={item.requestId}>
<span>{item.request.payload?.todo}</span>
{isOnline ? <progress value={item.uploading.progress} max={100} /> : <mark>waiting for network</mark>}
</li>
))}
</ol>
</article>
);
};

export const App = () => {
// The app manager owns the online state. The browser updates it, and so does the switch below.
const { isOnline, setOnline } = useAppManager(client);
const [saved, setSaved] = useState<Saved[]>([]);

const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
const todo = String(new FormData(form).get("todo"));
form.reset();

// Resolves when the server answers, which can be long after the click when the app is offline.
const { data, error } = await addTodo.send({ payload: { todo, completed: false, userId: 1 } });
if (error || !data) return;
setSaved((prev) => [{ ...data, savedAt: new Date().toLocaleTimeString() }, ...prev]);
};

return (
<main className="container">
<hgroup>
<h1>Offline queue</h1>
<p>Go offline, add a few todos, then go back online and watch the queue send them in order.</p>
</hgroup>
<label>
<input type="checkbox" role="switch" checked={isOnline} onChange={(event) => setOnline(event.target.checked)} />
{isOnline ? "Online" : "Offline"}
</label>
<form onSubmit={handleSubmit} role="group">
<input name="todo" placeholder="What needs doing?" required />
<button type="submit">Add</button>
</form>
<div className="grid-2">
<Queue />
<article>
<h6>Saved on the server ({saved.length})</h6>
{saved.length === 0 && <p className="muted">Nothing saved yet.</p>}
<ol className="list">
{saved.map((todo, index) => (
<li key={saved.length - index}>
<span>{todo.todo}</span>
<small className="muted">{todo.savedAt}</small>
</li>
))}
</ol>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/offline-queue hyper-fetch-react-offline-queue && cd hyper-fetch-react-offline-queue && npm install && npm run dev
What it shows
  1. offline: true keeps a request in the queue while the app is offline instead of failing it.
  2. queued: true sends the waiting requests one at a time, in the order they were made.
  3. useAppManager reads and sets the online state, so you can test offline mode without cutting your network.
  4. useQueue shows every request that is waiting or in flight.

How it works​

  1. api.ts creates addTodo with offline: true and queued: true. Mutations go to the client's submitDispatcher, which keeps them under the request's queryKey.

  2. The switch calls setOnline() from useAppManager(client). The AppManager normally follows the browser's online and offline events; the switch sets the same state by hand.

  3. handleSubmit calls addTodo.send(). While offline, the dispatcher keeps the request instead of sending it, and the promise stays pending:

    const { data, error } = await addTodo.send({ payload: { todo, completed: false, userId: 1 } });
  4. Queue calls useQueue(addTodo) and lists requests with their payload, upload progress, or a "waiting for network" mark.

  5. Going online emits the AppManager online event. The dispatcher flushes its queues, sends the todos one by one, and each send() resolves with the server response, which moves the todo to the saved list.

DummyJSON does not store new todos, so the saved list is built from the responses.

When to use it
  • Mobile and field apps used on unreliable connections.
  • Forms and actions that must not be lost when the network drops.
  • Changes that the server must receive in the order the user made them.

Summary

offline: true keeps requests in the dispatcher queue while the AppManager reports no connection, and queued: true sends them in order when it comes back. useQueue and useAppManager make both states visible in the UI.