Skip to content

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

Free

Promise Toast with Data Sonner for React

A Create User button whose toast says Creating user... and then John Doe has been added, using the name the promise returns.

Create User is an outline button. The toast says Creating user..., then after 2 seconds John Doe has been added. The name comes from the resolved value.

Use it when the success line should name what came back. A fixed success string cannot do that. If the result should stay on the page, use an Alert. In React, Base UI does not read the resolved name.

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">
    Create User
  </Button>
</>

FAQ

How does the success message get the name?

success is a function, (data) => the string with data.name and "has been added". The promise resolves after 2 seconds with { name: "John Doe" }, so the toast becomes "John Doe has been added".

What shows while the promise is pending?

loading is "Creating user...". That line is on screen until the promise resolves, in the same toast. toast.promise then swaps in the string the success function returns.

What is the error message in this file?

The string "Failed to create user". This button's promise always resolves, so the toast uses the success line. A rejection would show that error string as written.

What should the success function return?

A string. This file reads data.name from the resolved object and returns that sentence. The call also omits description.

How is the resolved value typed?

The promise is Promise<{ name: string }>. The data argument on success is that object, so data.name is a string. The timeout that resolves it is 2 seconds.

Does this demo render the toaster?

Yes. The demo renders its own Toaster beside the button; in an app, render one near the root. The loading state uses Toaster's spinning Loader2Icon until the success line replaces it.

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.