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
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
- idle
- pending
- slow
- success
- error
Legal from here: START
Transitions
| from | event | to |
|---|---|---|
| idle | START | pending |
| pending | SLOW | slow |
| pending | RESOLVE | success |
| pending | REJECT | error |
| slow | RESOLVE | success |
| slow | REJECT | error |
| success | START | pending |
| success | RESET | idle |
| error | START | pending |
| error | RESET | idle |
What just happened
Nothing yet. Press the button.
Usage
Drop it in
import { AsyncButton } from "@/app/lib/components/async-button";<AsyncButton onPress={() => fetch("/api/save", { method: "POST" })} />API
Props
| Prop | Type | Default |
|---|---|---|
onPress*The work. Resolve for success, reject (or throw) for failure. | () => Promise<unknown> | — |
labelsText for each state. Missing keys fall back to the defaults. | Partial<AsyncButtonLabels> | — |
slowAfterMsHow long a request runs before the button says it is slow. | number | 1200 |
successHoldMsHow long "success" stays before the button returns to idle. | number | 1600 |
reducedMotionForce reduced motion on or off. Leave undefined to follow the system setting. | boolean | — |
onStateChangeCalled on every state change, with the event that caused it. | (next: AsyncButtonState, event: AsyncButtonEvent) => void | — |
className | string | "" |
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.