Skip to documentation content

Undoable Action

Apply a change on screen at once, hold the request behind a visible countdown with Undo, and send it only when the time runs out.

undoable-action-demo

Overview

Undoable Action is the "Archived 3 conversations · Undo" bar. The change happens on screen the moment someone asks for it, but the request waits behind a short countdown. Undo during the countdown takes the change back and nothing is ever sent. When the countdown ends, the request goes out.

This suits actions that are easy to trigger and annoying to reverse on the server: archiving, deleting, moving, or bulk edits. Nobody is asked "Are you sure?", and a slip costs one click.

It differs from Async Action, which sends the request at once and offers Undo afterwards only when the server can reverse the action. Use Async Action when the server has a real reversal. Use Undoable Action when it does not, or when you would rather not call it.

Undoable Action does not send requests or store anything. You pass the change to make on screen and the request to send. It decides when to send it and when to take the change back.

Anatomy

UndoableAction
  • useUndoableActionThe queue: applies changes, runs countdowns, and sends requests
  • UndoBarOne region listing what is waiting or failed
    • EntryOne action
      • CountdownA ring that empties, and the seconds left
      • MessageWhat happened, in the past tense
      • UndoWhile the countdown runs
      • Retry and DismissAfter the request fails
    • AnnouncementA polite status region, one sentence per event

Installing undoable-action brings Button along as a registry dependency.

Behavior

The countdown

run calls your apply at once, adds an entry to the bar, and starts its countdown, six seconds unless you pass duration. While it runs, the entry offers Undo. When it ends, commit is called and the entry shows a spinner until the request settles.

The countdown holds while a mouse pointer is over the bar, while focus is inside it, and while the browser tab is hidden. Reading the message, reaching for Undo with the keyboard, or switching tabs never lets an action slip through.

Undo

Undo runs the rollback that apply returned and removes the entry. commit is never called, so the server never hears of the action. onUndo runs afterwards.

Failure

When commit rejects, the rollback runs, so the change is taken back on screen, and the entry stays with the error, Retry, and Dismiss. Retry applies the change again and sends it straight away, without another countdown: the person has already decided. onError runs with the error.

Several actions

Each action has its own entry and countdown, listed oldest first. At most three wait at once unless you pass max; a fourth sends the oldest straight away.

Leaving the page

When the component that called the hook unmounts, every waiting action is sent: nobody undid it, so it stands. A browser tab that closes during the countdown cannot run JavaScript reliably, so keep countdowns short and call flush from your own navigation if it matters.

Accessibility

UndoBar is a labelled region with a polite status inside it. Each new action is announced once with how long Undo stays available, such as "Archived 3 conversations. Undo is available for 6 seconds." Undo and failure are announced too. The ticking seconds are hidden from screen readers, so nothing chatters.

Because focus inside the bar holds every countdown, a keyboard or screen reader user has as long as they need to reach Undo. Each Undo button is named after its action, such as "Undo: Archived 3 conversations".

Undo removes the button that was pressed. Focus then moves to the next button in the bar, or to the bar itself when it is empty, so the next Tab continues from there.

The countdown ring follows reduced motion by stepping in tenths instead of sweeping. Failures carry an icon and a sentence, not color alone.

KeyAction
TabMove into the bar, which holds every countdown, then across Undo, Retry, and Dismiss
Enter or SpaceActivate the focused button

Installation

npx honestui@latest add undoable-action

Usage

Call the hook where the list's state lives, run an action from any control, and render one bar:

import { UndoBar, useUndoableAction } from "@/components/ui/undoable-action/undoable-action"

const undoable = useUndoableAction()

const archive = (ids: string[]) =>
  undoable.run({
    message: `Archived ${ids.length} conversations`,
    apply: () => {
      setInbox((current) => current.filter((item) => !ids.includes(item.id)))
      return () => setInbox((current) => restoreOrder(current, ids))
    },
    commit: ({ signal }) => api.archive(ids, { signal }),
  })

<UndoBar action={undoable} className="fixed inset-x-4 bottom-4 mx-auto max-w-md" />

Place the bar where it belongs in your layout: under a list, or fixed to the bottom of the screen. It takes no space while the queue is empty.

Wording

Write message in the past tense, because on screen the action has already happened. The other sentences come from labels, which also translates the bar:

<UndoBar
  action={undoable}
  labels={{
    failed: (message, error) => `${message} did not go through: ${describe(error)}`,
  }}
/>

Don't do this

Sending the request first

// Bad. The archive is already on the server, so Undo here only hides the truth.
commit: () => Promise.resolve(),
apply: () => { api.archive(ids); removeRows(ids) },

Send the request from commit. If it must go out at once, use Async Action with a real undo.

Calling the hook inside the row

The row disappears when apply runs, and a hook inside it would unmount with it, sending the request at once. Call the hook in the list, as in Usage.

Examples

Failure and retry

The first delete to reach the server is rejected. The file comes back, and the bar offers Retry, which sends the delete again without another countdown.

undoable-action-failure

API reference

useUndoableAction

useUndoableAction(options?) returns the queue.

OptionTypeDefaultDescription
durationnumber6000The countdown, in milliseconds.
maxnumber3How many actions may wait at once before the oldest is sent.

The queue

PropertyTypeDescription
entriesUndoableEntry[]Waiting, committing, and failed actions, oldest first.
pausedbooleanSomething is holding the countdowns.
run(options) => stringApplies a change, starts its countdown, and returns its id.
undo(id) => voidTakes back a waiting action.
retry(id) => voidRe-applies a failed action and sends it now.
dismiss(id) => voidRemoves a failed entry, or sends a waiting one now.
setPaused(reason, paused) => voidHolds or releases the countdowns, for your own reasons such as an open dialog.
flush() => voidSends every waiting action now.

run options

OptionTypeDefaultDescription
messagestringRequiredWhat happened, in the past tense.
commit({ signal }) => Promise<TResult>RequiredThe request, sent when the countdown ends.
apply() => (() => void) | voidNoneMakes the change on screen and returns its rollback.
durationnumberThe queue'sThis action's countdown.
onCommit(result) => voidNoneRuns after the request resolves.
onUndo() => voidNoneRuns after Undo.
onError(error) => voidNoneRuns after the request rejects and the rollback has run.

UndoBar

Accepts native section props beyond those listed.

PropTypeDefaultDescription
actionThe value from useUndoableActionRequiredThe queue to show.
labelsPartial<UndoBarLabels>EnglishThe region name, button names, and every sentence the bar writes.

Types

ExportShape
UndoableEntryid, message, phase (waiting, committing, or failed), duration, remaining, deadline, and error after a failure
UndoBarLabelsregion, undo, undoAction, retry, dismiss, committing, failed, added, undone, secondsLeft
createUndoableQueueThe store behind the hook, for use outside React