Skip to main content

Bulk actions

A table of todos with checkboxes. Select some and press Complete or Delete. Every row gets its own request, a progress bar counts the finished ones, and a failed row shows its error while the others succeed. Choose whether the requests run one at a time or all at once.

intermediatesenduseFetchmockingerrors
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";

import { getTodosRequest } from "./api";
import { useBulkAction } from "./use-bulk-action";
import type { RowStatus } from "./use-bulk-action";

const statusLabel: Record<RowStatus["state"], string> = {
waiting: "Waiting",
running: "Saving...",
done: "Done",
failed: "Failed",
};

export const App = () => {
const { data, error, loading } = useFetch(getTodosRequest);
const { statuses, run } = useBulkAction();
const [selected, setSelected] = useState<Set<number>>(new Set());
const [oneByOne, setOneByOne] = useState(true);
const [failSome, setFailSome] = useState(true);
const [running, setRunning] = useState(false);

const todos = data?.todos ?? [];
// Every third row fails while the switch is on, so you can see partial failures.
const failingIds = new Set(failSome ? todos.filter((_, index) => index % 3 === 2).map((todo) => todo.id) : []);

const results = Object.values(statuses);
const finished = results.filter((status) => status.state === "done" || status.state === "failed").length;
const failed = results.filter((status) => status.state === "failed").length;

const toggle = (id: number) =>
setSelected((current) => {
const next = new Set(current);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});

const handleAction = async (action: "complete" | "delete") => {
const chosen = todos.filter((todo) => selected.has(todo.id));
setRunning(true);
await run(action, chosen, { oneByOne, failingIds });
setRunning(false);
// Keep the failed rows selected, so a retry is one click away.
setSelected(new Set(chosen.filter((todo) => failingIds.has(todo.id)).map((todo) => todo.id)));
};

return (
<main className="container">
<hgroup>
<h1>Bulk actions</h1>
<p>Select todos and complete or delete them. Each row gets its own request and its own result.</p>
</hgroup>

<div className="options">
<fieldset>
<label>
<input type="radio" name="mode" checked={oneByOne} onChange={() => setOneByOne(true)} />
One at a time (shared queue)
</label>
<label>
<input type="radio" name="mode" checked={!oneByOne} onChange={() => setOneByOne(false)} />
All at once
</label>
</fieldset>
<label>
<input
type="checkbox"
role="switch"
checked={failSome}
onChange={(event) => setFailSome(event.target.checked)}
/>
Make every third row fail
</label>
</div>

<div className="toolbar">
<div role="group">
<button type="button" disabled={running || selected.size === 0} onClick={() => handleAction("complete")}>
Complete {selected.size}
</button>
<button
type="button"
className="secondary"
disabled={running || selected.size === 0}
onClick={() => handleAction("delete")}
>
Delete {selected.size}
</button>
</div>
{results.length > 0 && (
<div className="progress">
<progress value={finished} max={results.length} />
<small>
{finished} of {results.length} finished{failed > 0 && `, ${failed} failed`}
</small>
</div>
)}
</div>

{loading && !data && <p aria-busy="true">Loading todos...</p>}
{error && <p className="error">Could not load todos: {error.message}</p>}

<table>
<thead>
<tr>
<th>
<input
type="checkbox"
aria-label="Select all"
checked={todos.length > 0 && selected.size === todos.length}
onChange={(event) => setSelected(new Set(event.target.checked ? todos.map((todo) => todo.id) : []))}
/>
</th>
<th>Todo</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{todos.map((todo) => {
const status = statuses[todo.id];
return (
<tr key={todo.id}>
<td>
<input
type="checkbox"
aria-label={`Select ${todo.todo}`}
checked={selected.has(todo.id)}
onChange={() => toggle(todo.id)}
/>
</td>
<td>
{todo.completed ? <s>{todo.todo}</s> : todo.todo}
{failingIds.has(todo.id) && <small className="muted"> (will fail)</small>}
</td>
<td className={status?.state} aria-busy={status?.state === "running"}>
{status ? statusLabel[status.state] : ""}
{status?.message && <small> {status.message}</small>}
</td>
</tr>
);
})}
</tbody>
</table>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/bulk-actions hyper-fetch-react-bulk-actions && cd hyper-fetch-react-bulk-actions && npm install && npm run dev
What it shows
  1. One request per row with send(), so each row has its own status and error.
  2. queued: true plus a shared query key runs the requests one after another. Without the shared key they run in parallel.
  3. Partial failures: a failed row does not stop or undo the others, and it stays selected for a retry.
  4. Per-instance mocks: setMock on one request instance makes only that row fail.

How it works​

  1. api.ts creates both mutations with queued: true. Queued requests that share a query key run one at a time, in the order they were sent. By default the query key comes from the endpoint, and the endpoint holds the todo id, so every todo has its own queue and the requests run in parallel.

  2. In One at a time mode, useBulkAction gives every request the same key:

    let request = completeTodoRequest.setParams({ todoId: todo.id }).setPayload({ completed: true });
    if (oneByOne) request = request.setQueryKey("bulk-action");
  3. run() sends all requests and waits for them with Promise.all. send() never rejects, it resolves with success and error, so one failed row cannot break the loop. onRequestStart marks a row as running when its request really starts, which shows the queue at work.

  4. A successful row updates the cached list with client.cache.update(): completed todos are crossed out, deleted ones disappear. dummyjson does not store writes, so the cache is the only place the change lives.

  5. With Make every third row fail on, those rows get request.setMock(serverError). setMock changes only that instance, so the other rows still go to dummyjson.

  6. The progress bar counts rows that are done or failed. After the run, failed rows stay selected so you can try again.

When to use it
  • Admin lists, inboxes and tables where people act on many rows at once.
  • Use one at a time when the server is rate limited or the order matters, all at once when speed matters. If your API has a bulk endpoint, one request for all rows is simpler still, but you lose the per-row result.

Summary

One request per row gives every row its own result. queued with a shared query key runs them in a line, separate keys run them together, and send() resolving with the response keeps partial failures from breaking the batch.