# 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.

Source: https://www.honestui.com/docs/product/undoable-action

```tsx
"use client"

import * as React from "react"
import { Archive as ArchiveIcon } from "honestui/icons"

import { Button } from "@/components/honest-ui/ui/button"
import {
  UndoBar,
  useUndoableAction,
} from "@/registry/default/product/undoable-action/undoable-action"

type Conversation = { id: string; from: string; subject: string; read: boolean }

// Sample conversations.
const sampleInbox: Conversation[] = [
  { id: "c1", from: "Maya Chen", subject: "Q4 roadmap review notes", read: false },
  { id: "c2", from: "Billing", subject: "Invoice #1042 is paid", read: true },
  { id: "c3", from: "Jonas Weber", subject: "Re: Staging deploy freeze", read: true },
  { id: "c4", from: "GitHub", subject: "3 new review requests", read: true },
  { id: "c5", from: "Priya Natarajan", subject: "Offsite agenda, first draft", read: false },
]

function wait(milliseconds: number) {
  return new Promise((resolve) => window.setTimeout(resolve, milliseconds))
}

const rowText =
  "[font-size:var(--hui-font-size-regular)] [letter-spacing:var(--hui-letter-spacing-regular)] [line-height:20px]"
const metaText =
  "[font-size:var(--hui-font-size-small)] [letter-spacing:var(--hui-letter-spacing-small)] [line-height:var(--hui-line-height-small)]"

/**
 * Nothing is sent until a countdown ends; the request is a timer here. Each
 * archive leaves the list at once, and Undo puts it back in its place.
 */
export function UndoableActionDemo() {
  const [inbox, setInbox] = React.useState(sampleInbox)
  const undoable = useUndoableAction({ duration: 6000 })

  // Put conversations back in their original order, whatever else changed meanwhile.
  const restore = (ids: string[]) => () =>
    setInbox((current) =>
      sampleInbox.filter((item) => ids.includes(item.id) || current.some((kept) => kept.id === item.id))
    )

  const archive = (items: Conversation[]) => {
    const ids = items.map((item) => item.id)
    undoable.run({
      message:
        items.length === 1 ? `Archived “${items[0].subject}”` : `Archived ${items.length} conversations`,
      apply: () => {
        setInbox((current) => current.filter((item) => !ids.includes(item.id)))
        return restore(ids)
      },
      commit: () => wait(500),
    })
  }

  const read = inbox.filter((item) => item.read)

  return (
    <div className="relative flex w-full max-w-lg min-w-0 flex-col gap-[var(--hui-space-4)] pb-[var(--hui-space-2)]">
      <div className="flex min-w-0 items-center justify-between gap-[var(--hui-space-4)]">
        <p className={`m-0 text-[var(--hui-color-foreground-base-secondary)] tabular-nums ${metaText}`}>
          {inbox.length} in inbox
        </p>
        <Button
          variant="outline"
          size="sm"
          disabled={read.length === 0}
          className="shadow-none px-[var(--hui-space-4)] [font-size:var(--hui-font-size-small)] [font-weight:var(--hui-font-weight-medium)]"
          onClick={() => archive(read)}
        >
          {read.length === 0 ? "Archive read" : `Archive ${read.length} read`}
        </Button>
      </div>

      {inbox.length === 0 ? (
        <p className={`m-0 flex min-h-14 items-center justify-center rounded-[var(--hui-radius-3)] border-[0.5px] border-[var(--hui-color-border-base-primary)] px-[var(--hui-space-5)] text-[var(--hui-color-foreground-base-secondary)] ${metaText}`}>
          Inbox zero.
        </p>
      ) : (
        <ul
          aria-label="Inbox"
          className="m-0 list-none overflow-hidden rounded-[var(--hui-radius-3)] border-[0.5px] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] p-0 shadow-[var(--hui-shadow-feather)] [&>*+*]:border-t-[0.5px] [&>*+*]:border-t-[var(--hui-color-border-base-primary)]"
        >
          {inbox.map((item) => (
            <li
              key={item.id}
              className="flex min-h-14 min-w-0 items-center gap-[var(--hui-space-4)] px-[var(--hui-space-5)] py-[var(--hui-space-3)]"
            >
              <span
                aria-hidden="true"
                className={`size-1.5 shrink-0 rounded-full ${item.read ? "bg-transparent" : "bg-[var(--hui-color-foreground-base-primary)]"}`}
              />
              <span className="flex min-w-0 flex-1 flex-col">
                <span className={`min-w-0 truncate text-[var(--hui-color-foreground-base-primary)] ${rowText} ${item.read ? "" : "[font-weight:var(--hui-font-weight-medium)]"}`}>
                  {item.subject}
                </span>
                <span className={`min-w-0 truncate text-[var(--hui-color-foreground-base-secondary)] ${metaText}`}>
                  {item.from}
                  {item.read ? "" : " · Unread"}
                </span>
              </span>
              <Button
                variant="ghost"
                size="icon-sm"
                aria-label={`Archive “${item.subject}”`}
                className="size-7 min-h-7 shrink-0 text-[var(--hui-color-foreground-base-secondary)] shadow-none [&_svg]:size-3.5"
                onClick={() => archive([item])}
              >
                <ArchiveIcon aria-hidden="true" />
              </Button>
            </li>
          ))}
        </ul>
      )}

      <UndoBar action={undoable} />
    </div>
  )
}

```

## Overview [#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](/docs/product/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 [#anatomy]

<Anatomy title="UndoableAction">
  <AnatomyItem name="useUndoableAction" description="The queue: applies changes, runs countdowns, and sends requests" />

  <AnatomyItem name="UndoBar" description="One region listing what is waiting or failed">
    <AnatomyItem name="Entry" description="One action">
      <AnatomyItem name="Countdown" description="A ring that empties, and the seconds left" />

      <AnatomyItem name="Message" description="What happened, in the past tense" />

      <AnatomyItem name="Undo" description="While the countdown runs" />

      <AnatomyItem name="Retry and Dismiss" description="After the request fails" />
    </AnatomyItem>

    <AnatomyItem name="Announcement" description="A polite status region, one sentence per event" />
  </AnatomyItem>
</Anatomy>

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

## Behavior [#behavior]

### The countdown [#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]

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 [#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 [#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 [#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 [#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 <kbd>Tab</kbd> 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.

| Key                                  | Action                                                                               |
| ------------------------------------ | ------------------------------------------------------------------------------------ |
| <kbd>Tab</kbd>                       | Move into the bar, which holds every countdown, then across Undo, Retry, and Dismiss |
| <kbd>Enter</kbd> or <kbd>Space</kbd> | Activate the focused button                                                          |

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;undoable-action&#x22;]" />
  

  
    
      
        No extra packages are needed beyond the base setup.
      

      
        Copy and paste these files into your project.
      

      <ComponentSource name="undoable-action" title="components/ui/undoable-action/undoable-action-types.ts" file="undoable-action-types.ts" />

      <ComponentSource name="undoable-action" title="components/ui/undoable-action/undoable-action-utils.ts" file="undoable-action-utils.ts" />

      <ComponentSource name="undoable-action" title="components/ui/undoable-action/use-undoable-action.ts" file="use-undoable-action.ts" />

      <ComponentSource name="undoable-action" title="components/ui/undoable-action/undoable-action.tsx" file="undoable-action.tsx" />

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

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

```tsx
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 [#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:

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

## Don't do this [#dont-do-this]

### Sending the request first [#sending-the-request-first]

```tsx
// 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](/docs/product/async-action) with a real `undo`.

### Calling the hook inside the row [#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 [#examples]

### Failure and retry [#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.

```tsx
"use client"

import * as React from "react"
import { Trash2 as TrashIcon } from "honestui/icons"

import { Button } from "@/components/honest-ui/ui/button"
import {
  UndoBar,
  useUndoableAction,
} from "@/registry/default/product/undoable-action/undoable-action"

type File = { id: string; name: string; size: string }

// Sample files.
const sampleFiles: File[] = [
  { id: "f1", name: "brand-guidelines-v3.pdf", size: "4.2 MB" },
  { id: "f2", name: "q3-board-deck.key", size: "18.6 MB" },
  { id: "f3", name: "headshots.zip", size: "212 MB" },
]

function wait(milliseconds: number) {
  return new Promise((resolve) => window.setTimeout(resolve, milliseconds))
}

const metaText =
  "[font-size:var(--hui-font-size-small)] [letter-spacing:var(--hui-letter-spacing-small)] [line-height:var(--hui-line-height-small)]"

/**
 * The first delete to reach the "server" is rejected. The file comes back and
 * the bar offers Retry, which sends it again straight away.
 */
export function UndoableActionFailure() {
  const [files, setFiles] = React.useState(sampleFiles)
  const attempts = React.useRef(0)
  const undoable = useUndoableAction({ duration: 4000 })

  const remove = (file: File) =>
    undoable.run({
      message: `Deleted ${file.name}`,
      apply: () => {
        setFiles((current) => current.filter((item) => item.id !== file.id))
        return () =>
          setFiles((current) =>
            sampleFiles.filter((item) => item.id === file.id || current.some((kept) => kept.id === item.id))
          )
      },
      commit: async () => {
        await wait(600)
        attempts.current += 1
        if (attempts.current === 1) throw new Error("The storage service is unavailable.")
      },
    })

  return (
    <div className="flex w-full max-w-lg min-w-0 flex-col gap-[var(--hui-space-4)] pb-[var(--hui-space-2)]">
      <ul
        aria-label="Shared files"
        className="m-0 list-none overflow-hidden rounded-[var(--hui-radius-3)] border-[0.5px] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] p-0 shadow-[var(--hui-shadow-feather)] [&>*+*]:border-t-[0.5px] [&>*+*]:border-t-[var(--hui-color-border-base-primary)]"
      >
        {files.map((file) => (
          <li
            key={file.id}
            className="flex min-h-12 min-w-0 items-center justify-between gap-[var(--hui-space-4)] px-[var(--hui-space-5)] py-[var(--hui-space-2)]"
          >
            <span className="flex min-w-0 items-baseline gap-[var(--hui-space-3)]">
              <span className="min-w-0 truncate font-mono text-[var(--hui-color-foreground-base-primary)] [font-size:var(--hui-font-size-small)] [line-height:20px]">
                {file.name}
              </span>
              <span className={`shrink-0 text-[var(--hui-color-foreground-base-secondary)] tabular-nums ${metaText}`}>
                {file.size}
              </span>
            </span>
            <Button
              variant="ghost"
              size="icon-sm"
              aria-label={`Delete ${file.name}`}
              className="size-7 min-h-7 shrink-0 text-[var(--hui-color-foreground-base-secondary)] shadow-none [&_svg]:size-3.5"
              onClick={() => remove(file)}
            >
              <TrashIcon aria-hidden="true" />
            </Button>
          </li>
        ))}
        {files.length === 0 && (
          <li className={`flex min-h-12 items-center justify-center px-[var(--hui-space-5)] text-[var(--hui-color-foreground-base-secondary)] ${metaText}`}>
            No shared files.
          </li>
        )}
      </ul>
      <UndoBar
        action={undoable}
        labels={{
          region: "Recent file actions",
          failed: (message, error) =>
            `${message.replace(/^Deleted/, "Could not delete")}. ${error instanceof Error ? error.message : ""} It is back in the list.`,
        }}
      />
    </div>
  )
}

```

## API reference [#api-reference]

### useUndoableAction [#useundoableaction]

`useUndoableAction(options?)` returns the queue.

| Option     | Type   | Default | Description                                                  |
| ---------- | ------ | ------- | ------------------------------------------------------------ |
| `duration` | number | `6000`  | The countdown, in milliseconds.                              |
| `max`      | number | `3`     | How many actions may wait at once before the oldest is sent. |

### The queue [#the-queue]

| Property    | Type                       | Description                                                                    |
| ----------- | -------------------------- | ------------------------------------------------------------------------------ |
| `entries`   | `UndoableEntry[]`          | Waiting, committing, and failed actions, oldest first.                         |
| `paused`    | boolean                    | Something is holding the countdowns.                                           |
| `run`       | `(options) => string`      | Applies a change, starts its countdown, and returns its id.                    |
| `undo`      | `(id) => void`             | Takes back a waiting action.                                                   |
| `retry`     | `(id) => void`             | Re-applies a failed action and sends it now.                                   |
| `dismiss`   | `(id) => void`             | Removes a failed entry, or sends a waiting one now.                            |
| `setPaused` | `(reason, paused) => void` | Holds or releases the countdowns, for your own reasons such as an open dialog. |
| `flush`     | `() => void`               | Sends every waiting action now.                                                |

### run options [#run-options]

| Option     | Type                               | Default     | Description                                              |
| ---------- | ---------------------------------- | ----------- | -------------------------------------------------------- |
| `message`  | string                             | Required    | What happened, in the past tense.                        |
| `commit`   | `({ signal }) => Promise<TResult>` | Required    | The request, sent when the countdown ends.               |
| `apply`    | `() => (() => void) \| void`       | None        | Makes the change on screen and returns its rollback.     |
| `duration` | number                             | The queue's | This action's countdown.                                 |
| `onCommit` | `(result) => void`                 | None        | Runs after the request resolves.                         |
| `onUndo`   | `() => void`                       | None        | Runs after Undo.                                         |
| `onError`  | `(error) => void`                  | None        | Runs after the request rejects and the rollback has run. |

### UndoBar [#undobar]

Accepts native section props beyond those listed.

| Prop     | Type                               | Default  | Description                                                       |
| -------- | ---------------------------------- | -------- | ----------------------------------------------------------------- |
| `action` | The value from `useUndoableAction` | Required | The queue to show.                                                |
| `labels` | `Partial<UndoBarLabels>`           | English  | The region name, button names, and every sentence the bar writes. |

### Types [#types]

| Export                | Shape                                                                                                                             |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `UndoableEntry`       | `id`, `message`, `phase` (`waiting`, `committing`, or `failed`), `duration`, `remaining`, `deadline`, and `error` after a failure |
| `UndoBarLabels`       | `region`, `undo`, `undoAction`, `retry`, `dismiss`, `committing`, `failed`, `added`, `undone`, `secondsLeft`                      |
| `createUndoableQueue` | The store behind the hook, for use outside React                                                                                  |
