useUndoBatch
Batches undoable actions into one Sonner toast whose Undo restores them all and retries what failed.
For actions that are quick to do and safe to reverse, such as archiving: do the action at once, then push how to undo it. Every push while the toast is open joins one batch and the message counts again (3 tasks archived); the toast's Undo reverses the whole batch, newest first. count is how many things one entry stands for, durationMs how long the toast stays (6000 by default), and id keeps two batches on one screen apart. An undo that fails stays in the batch and the toast returns as an error, so Undo tries again. The hook binds no key: undo() reverses the last batch from your own handler, even after the toast has gone, and clear() forgets it. The page needs one Toaster from @khaeli/sonner.
Archive with undo
- Write the migration guide
- Add shortcuts to the editor
- Fix the export time zone
- Review the pricing page copy
"use client"
import { ArchiveIcon } from "@keyline-icons/react"
import { useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Toaster } from "@/components/ui/sonner"
import { useUndoBatch } from "@/hooks/use-undo-batch"
const tasks = [
{ id: "T-318", title: "Write the migration guide" },
{ id: "T-317", title: "Add shortcuts to the editor" },
{ id: "T-314", title: "Fix the export time zone" },
{ id: "T-309", title: "Review the pricing page copy" },
]
export default function UseUndoBatchArchiveWithUndo() {
const [archived, setArchived] = useState<string[]>([])
const list = useRef<HTMLDivElement>(null)
const batch = useUndoBatch({
id: "archive-tasks",
message: (count) => `${count} ${count === 1 ? "task" : "tasks"} archived`,
})
const open = tasks.filter((task) => !archived.includes(task.id))
function archive(ids: string[]) {
setArchived((current) => [...current, ...ids])
// One entry per action: `count` says how many tasks it stands for.
batch.push({
count: ids.length,
undo: () => setArchived((current) => current.filter((id) => !ids.includes(id))),
})
}
return (
<div ref={list} tabIndex={-1} className="flex w-full max-w-sm flex-col gap-3 outline-none">
{open.length > 0 ? (
<ul className="divide-y divide-border border-y border-border">
{open.map((task) => (
<li key={task.id} className="flex items-center justify-between gap-2 py-1.5">
<span className="min-w-0 truncate">{task.title}</span>
<Button
variant="ghost"
size="icon"
aria-label={`Archive ${task.title}`}
onClick={(event) => {
// The row is about to go: hand focus to a neighbour first, or to the list.
const row = event.currentTarget.closest("li")
const neighbour = row?.nextElementSibling ?? row?.previousElementSibling
;(neighbour?.querySelector("button") ?? list.current)?.focus()
archive([task.id])
}}
>
<ArchiveIcon />
</Button>
</li>
))}
</ul>
) : (
<p className="border-y border-border py-3 text-muted-foreground">Every task is archived.</p>
)}
<Button
variant="outline"
className="self-start"
disabled={open.length === 0}
onClick={() => {
list.current?.focus()
archive(open.map((task) => task.id))
}}
>
Archive all
</Button>
<Toaster />
</div>
)
}
Installation
npx shadcn@latest add @khaeli/use-undo-batchbunx --bun shadcn@latest add @khaeli/use-undo-batchInstalls with
- npm packages
- sonner ^2.0.8
Keyboard
EnterSpace- On a row's button, archives the task. Move focus to the next row first, since the pressed button leaves the page.
Alt T- Moves focus to the toasts, where Tab reaches Undo. The key belongs to @khaeli/sonner.
Accessible name
- The toast is announced when it appears, without moving focus. Write
messageas a full phrase with the number in it: 2 tasks archived. - A button that repeats on every row is named after its row: Archive Write the migration guide.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/use-undo-batch.json