Async Status Button
Button that runs a promise-returning handler and cycles through idle, pending, success and error by itself, swapping its icon and label. Use it for a save, send or export that settles in a few seconds.
How it differs. The base four-state machine: width is floored at the idle measurement, presses while pending are ignored through aria-disabled so focus stays put, and every transition is announced.
Install
pnpm dlx shadcn@latest add @hazine/async-button-status-cycleAdds 1 file, 1 shadcn primitive (button), 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
The demo in the preview, 231 lines
"use client"
import * as React from "react"
import { Download, KeyRound, Rocket, Save, Send } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { AsyncButtonStatusCycle } from "@/components/hazine/async-button-status-cycle"
const ROW_COUNT = new Intl.NumberFormat("en-US").format(1284)
function wait(milliseconds: number) {
return new Promise<void>((resolve) => setTimeout(resolve, milliseconds))
}
export default function AsyncButtonStatusCycleDemo() {
const id = React.useId()
const tallyId = React.useId()
const [url, setUrl] = React.useState("https://api.cedarline.example")
const [tally, setTally] = React.useState({ sent: 0, delivered: 0 })
async function sendTestEvent() {
await wait(1400)
const delivered = url.trim().startsWith("https://")
setTally((previous) => ({
sent: previous.sent + 1,
delivered: previous.delivered + (delivered ? 1 : 0),
}))
if (!delivered) throw new Error("Endpoint rejected")
}
return (
<div className="w-full">
<div className="@container mx-auto grid max-w-md gap-2">
<Label htmlFor={id}>Webhook endpoint</Label>
<div className="flex flex-col gap-2 @sm:flex-row">
<Input
id={id}
type="url"
inputMode="url"
autoComplete="off"
spellCheck={false}
value={url}
onChange={(event) => setUrl(event.target.value)}
aria-describedby={tallyId}
className="font-mono"
/>
<AsyncButtonStatusCycle
icon={<Send aria-hidden="true" />}
onAction={sendTestEvent}
pendingLabel="Sending"
successLabel="Delivered"
errorLabel="Rejected"
pendingMessage="Sending a test event."
successMessage="Test event delivered."
errorMessage="Test event rejected. Use an https endpoint and send again."
>
Send test event
</AsyncButtonStatusCycle>
</div>
<p id={tallyId} className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{tally.sent === 0
? "No test events sent yet."
: `${tally.delivered} of ${tally.sent} test ${tally.sent === 1 ? "event" : "events"} delivered.`}
</span>{" "}
Endpoints that do not start with https are rejected.
</p>
</div>
</div>
)
}
function AsyncButtonStatusCycleLoading() {
return (
<div className="grid max-w-md justify-items-start gap-2">
<AsyncButtonStatusCycle
status="pending"
icon={<Save aria-hidden="true" />}
pendingLabel="Saving"
pendingMessage="Saving notification settings."
>
Save changes
</AsyncButtonStatusCycle>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
Writing 4 notification settings.
</span>{" "}
The button keeps focus and ignores presses until the request settles.
</p>
</div>
)
}
function AsyncButtonStatusCycleSuccess() {
return (
<div className="grid max-w-md justify-items-start gap-2">
<AsyncButtonStatusCycle
status="success"
icon={<Save aria-hidden="true" />}
successLabel="Saved"
successMessage="Notification settings saved."
>
Save changes
</AsyncButtonStatusCycle>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
4 notification settings saved.
</span>{" "}
A result stays for two seconds by default, then the label returns to
Save changes.
</p>
</div>
)
}
function AsyncButtonStatusCycleError() {
return (
<div className="grid max-w-md justify-items-start gap-2">
<AsyncButtonStatusCycle
status="error"
icon={<Save aria-hidden="true" />}
errorLabel="Not saved"
errorMessage="Notification settings were not saved. Check your connection and save again."
>
Save changes
</AsyncButtonStatusCycle>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
0 of 4 notification settings saved.
</span>{" "}
Pressing the button again starts a new attempt straight away.
</p>
</div>
)
}
function AsyncButtonStatusCycleDisabled() {
const reasonId = React.useId()
return (
<div className="grid max-w-md justify-items-start gap-2">
<AsyncButtonStatusCycle
disabled
aria-describedby={reasonId}
icon={<Rocket aria-hidden="true" />}
pendingLabel="Publishing"
successLabel="Published"
>
Publish release
</AsyncButtonStatusCycle>
<p id={reasonId} className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
2 of 3 required checks passed.
</span>{" "}
Publishing opens when the accessibility check finishes.
</p>
</div>
)
}
function AsyncButtonStatusCycleOverflow() {
const label =
"Regenerate the signing secret for the production environment"
return (
<div className="grid w-full max-w-64 justify-items-start gap-2">
<AsyncButtonStatusCycle
variant="outline"
title={label}
icon={<KeyRound aria-hidden="true" />}
onAction={() => wait(1400)}
pendingLabel="Regenerating the signing secret"
successLabel="Secret regenerated"
successMessage="Signing secret regenerated for production."
>
{label}
</AsyncButtonStatusCycle>
<p className="text-sm text-muted-foreground">
A label wider than its column is cut with an ellipsis and the button
never grows past the column.
</p>
</div>
)
}
function AsyncButtonStatusCycleRetry() {
const [attempts, setAttempts] = React.useState(0)
async function exportRows() {
await wait(1600)
const attempt = attempts + 1
setAttempts(attempt)
if (attempt % 2 === 1) throw new Error("Export timed out")
}
return (
<div className="grid max-w-md justify-items-start gap-2">
<AsyncButtonStatusCycle
variant="outline"
icon={<Download aria-hidden="true" />}
onAction={exportRows}
resetDelay={4000}
pendingLabel="Exporting"
successLabel="Exported"
errorLabel="Timed out"
pendingMessage={`Exporting ${ROW_COUNT} rows.`}
successMessage={`${ROW_COUNT} rows exported to orders.csv.`}
errorMessage="The export timed out. Press the button to try again."
>
Export {ROW_COUNT} rows
</AsyncButtonStatusCycle>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{attempts === 0
? "Not exported yet."
: `${attempts} ${attempts === 1 ? "attempt" : "attempts"} so far.`}
</span>{" "}
Odd attempts time out and even attempts finish. The result stays for
four seconds, and pressing it starts the next attempt.
</p>
</div>
)
}
export const scenarios = {
loading: AsyncButtonStatusCycleLoading,
success: AsyncButtonStatusCycleSuccess,
error: AsyncButtonStatusCycleError,
disabled: AsyncButtonStatusCycleDisabled,
overflow: AsyncButtonStatusCycleOverflow,
retry: AsyncButtonStatusCycleRetry,
}
Props12
- onAction
- () => Promise<unknown> | void
- Runs on press. The button is pending until the returned promise settles, then shows success when it resolved and error when it rejected. Without it the button only reflects `status`.
- status
- AsyncButtonStatus
- Controlled status. The width is held only for runs started by a press at rest, because that is the one moment the idle width can be measured.
- defaultStatus
- AsyncButtonStatus = "idle"
- onStatusChange
- (status: AsyncButtonStatus) => void
- resetDelay
- number = 2000
- Milliseconds a result stays visible before the button returns to idle. Pass `Infinity` to hold the result until the next press.
- icon
- React.ReactNode
- Leading icon at rest. The spinner, check and alert take its place. It is hidden from assistive technology, the label carries the name.
- pendingLabel
- string = "Working"
- Visible labels. Keep them no longer than the idle label so the width holds.
- successLabel
- string = "Done"
- errorLabel
- string = "Failed"
- pendingMessage
- string = pendingLabel
- Announced when a run starts. Defaults to `pendingLabel`.
- successMessage
- string = successLabel
- Announced when the promise resolves. Defaults to `successLabel`.
- errorMessage
- string = "Failed. Press the button to try again."
- Announced as an alert when the promise rejects. Say what to do next.
Also accepts every prop of Omit<React.ComponentProps<typeof Button>, "asChild">.
Accessibility
- Keyboard
Keyboard support for Async Status Button Key Effect Enter or Space Starts the action. While it is pending the press is ignored and focus stays on the button Enter or Space on a result Starts a new run without waiting for the label to return to rest - Screen reader
A native button that sets aria-disabled and aria-busy while pending, so it stays focusable. Icons are decorative, the label names each state. Pending and success go to a status region, a failure to an alert region.
- Announces: {pendingMessage}
- Announces: {successMessage}
- Announces: {errorMessage}
- Reduced motion
- The loader icon does not rotate. The icon and label still change, without a transition.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- button
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.