Skip to content

Async button

Button driven by a five-state machine (idle, pending, slow, success, error). It stays focusable while it works, ignores presses it cannot honour, says out loud when a request is slow, and offers a retry on failure. The demo shows the live state, the legal transitions and an event log. With reduced motion the moving progress bar becomes a still one and the colour change is instant.

  • State Machine
  • useReducer
  • aria-live
  • prefers-reduced-motion

async-button

The next request

Press it with the keyboard: Tab to focus, Enter or Space to press. Press it twice while it works: the second press is ignored. Past 1.2 s it says so instead of spinning forever.

State

  1. idle
  2. pending
  3. slow
  4. success
  5. error

Legal from here: START

Transitions

fromeventto
idleSTARTpending
pendingSLOWslow
pendingRESOLVEsuccess
pendingREJECTerror
slowRESOLVEsuccess
slowREJECTerror
successSTARTpending
successRESETidle
errorSTARTpending
errorRESETidle

What just happened

Nothing yet. Press the button.

Usage

Drop it in

import
import { AsyncButton } from "@/app/lib/components/async-button";
example 1
<AsyncButton onPress={() => fetch("/api/save", { method: "POST" })} />

API

Props

PropTypeDefault
onPress*

The work. Resolve for success, reject (or throw) for failure.

() => Promise<unknown>—
labels

Text for each state. Missing keys fall back to the defaults.

Partial<AsyncButtonLabels>—
slowAfterMs

How long a request runs before the button says it is slow.

number1200
successHoldMs

How long "success" stays before the button returns to idle.

number1600
reducedMotion

Force reduced motion on or off. Leave undefined to follow the system setting.

boolean—
onStateChange

Called on every state change, with the event that caused it.

(next: AsyncButtonState, event: AsyncButtonEvent) => void—
classNamestring""

Read from the component's source at build time. * required.

Accessibility

Works with

Cursor
Reacts to where the pointer is, not just whether it's over the element.
Touch
Follows your finger while it's down, then settles a moment after you lift.
Keyboard
Focus lights it up the way the cursor does. Every action has a key.
Reduced motion
Nothing moves or springs. Colour still answers, without drifting.