Number 33: Toast that follows a request
Specification
- Catalogue
- No. 33 of 110
- Section
- Overlays and toasts
- Interaction
- Loading, Feedback
- Element
- Toast
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
A small notice says a request is on its way, then whether it worked, with Retry when it did not.
The visitor can carry on while it works. A success leaves by itself, never while being read; a failure stays until dismissed and can be retried without starting again.
Enters 250ms from 10px below; success leaves after 4s, paused on hover and focus. Announced politely, never takes focus; at most three at once. Make it fail shows the error path and a working Retry; the request is simulated.
Code
React and plain CSS"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./promise-toast.css";
type Toast = { id: number; state: "pending" | "done" | "error" };
function PromiseToastDemo() {
const [toasts, setToasts] = useState<Toast[]>([]);
const [fail, setFail] = useState(false);
const next = useRef(1);
const timers = useRef(new Set<number>());
const failRef = useRef(fail);
useEffect(() => {
failRef.current = fail;
}, [fail]);
const sendBtn = useRef<HTMLButtonElement>(null);
useEffect(() => {
const t = timers.current;
return () => t.forEach((id) => window.clearTimeout(id));
}, []);
const later = (fn: () => void, ms: number) => {
const id = window.setTimeout(() => {
timers.current.delete(id);
fn();
}, ms);
timers.current.add(id);
return id;
};
const dismiss = useCallback((id: number) => setToasts((ts) => ts.filter((t) => t.id !== id)), []);
// Simulated request: 1.4s, then success or failure. A real build awaits the actual request.
const run = (id: number) => {
setToasts((ts) => ts.map((t) => (t.id === id ? { ...t, state: "pending" } : t)));
later(() => setToasts((ts) => ts.map((t) => (t.id === id ? { ...t, state: failRef.current ? "error" : "done" } : t))), 1400);
};
const send = () => {
const id = next.current++;
setToasts((ts) => [...ts.slice(-2), { id, state: "pending" }]);
run(id);
};
return (
<div className="dm pt">
<div className="pt-controls">
<button ref={sendBtn} type="button" className="dm-btn" data-variant="solid" onClick={send}>
Send invoice
</button>
<label className="ah-switch">
<input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} />
Make it fail
</label>
</div>
<ol className="pt-stack" aria-live="polite" aria-label="Notifications">
{toasts.map((t) => (
<ToastRow
key={t.id}
toast={t}
onDismiss={dismiss}
onClose={() => {
// Closed by hand: focus goes back to the button that started it, not to the page.
dismiss(t.id);
sendBtn.current?.focus();
}}
onRetry={() => run(t.id)}
/>
))}
</ol>
</div>
);
}
function ToastRow({ toast, onDismiss, onClose, onRetry }: { toast: Toast; onDismiss: (id: number) => void; onClose: () => void; onRetry: () => void }) {
const [held, setHeld] = useState(false);
const row = useRef<HTMLLIElement>(null);
// Success leaves after 4s, never while the pointer or focus is on it. Errors stay until dismissed.
useEffect(() => {
if (toast.state !== "done" || held) return;
const id = window.setTimeout(() => onDismiss(toast.id), 4000);
return () => window.clearTimeout(id);
}, [toast.state, toast.id, held, onDismiss]);
return (
<li
ref={row}
tabIndex={-1}
className="pt-toast"
data-state={toast.state}
onPointerEnter={() => setHeld(true)}
onPointerLeave={() => setHeld(false)}
onFocus={() => setHeld(true)}
onBlur={() => setHeld(false)}
>
<span className="pt-icon" aria-hidden="true">
{toast.state === "pending" ? (
<svg viewBox="0 0 24 24" width="18" height="18" className="pt-spin">
<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="2.4" strokeDasharray="40 20" strokeLinecap="round" />
</svg>
) : toast.state === "done" ? (
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
<path d="m5 12.5 4.5 4.5L19 7.5" />
</svg>
) : (
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
<path d="M12 7v6M12 17h.01" />
</svg>
)}
</span>
<span className="pt-text">
{toast.state === "pending" && "Sending invoice INV-0142 to Harbour Café…"}
{toast.state === "done" && "Invoice INV-0142 sent to Harbour Café."}
{toast.state === "error" && "Not sent: the connection dropped. Your draft is kept."}
</span>
{toast.state === "error" && (
<button
type="button"
className="pt-act"
onClick={() => {
// The buttons leave while it retries; keep focus on the toast itself.
row.current?.focus();
onRetry();
}}
>
Retry
</button>
)}
{toast.state !== "pending" && (
<button type="button" className="pt-act" aria-label="Dismiss" onClick={onClose}>
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" />
</svg>
</button>
)}
</li>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [{ click: ".dm-btn", text: "Send invoice", wait: 3800 }];
export default function PromiseToastEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Toast that follows a request" tour={TOUR}>
<PromiseToastDemo />
</PieceStage>
);
}