Skip to content

shadcn.io is an independent project built on shadcn/ui

Free

Promise Toast with Error Sonner for React

A Save Changes button whose toast says Saving changes... and then Error: Network error after the promise fails.

Save Changes is an outline button. The toast says Saving changes..., then after 2 seconds Error: Network error. The success line is not shown.

Use it when a failed request should keep the same toast and show the error's message. A failure that needs a retry on the page is an Alert. In React, Base UI does not catch the rejection.

Preview

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.
Use email insteadNo credit card

Anatomy

Sonner anatomy: toaster, toast, title, description, action

Usage

<>
  <Toaster />
  <Button onClick={handleShowToast} variant="outline">
    Save Changes
  </Button>
</>

FAQ

How does the error line get the message?

error is a function, (error: Error) => a string that reads error.message. The promise rejects after 2 seconds with new Error("Network error"), so the toast becomes Error: Network error.

What shows before the rejection?

loading is "Saving changes...". That stays on the same toast until the promise rejects. The error function's string then replaces it.

Is the success string used?

success is "Changes saved successfully", and this button's promise always calls reject. A resolve would show that string as written.

What does the error function receive?

The rejection from the promise. This demo rejects with an Error, then reads message. The function returns a string, which is the toast title.

How long does the error toast stay?

This call does not pass duration. After the swap off the loading type, the toast uses duration on Toaster, or 4 seconds when that is omitted.

Where does the spinner come from?

Toaster's icons.loading, a Loader2Icon with animate-spin. The demo renders its own Toaster beside the button; in an app, render one near the root.

API Reference

Sonner

No extra props in this demo. The rest is on the Sonner page.

Button

Sets onClick={handleShowToast} and variant="outline". The rest is on the Button page.