Actions

Control your notifications with ease using these built-in actions.

useToast()

The useToast function is an entry point to managing the toasts. It returns functions for showing, updating, dismissing and removing toasts, as well as to access the queue.

import { useToast } from "solid-notifications";

function App() {
  const { notify, update, dismiss, remove, promise, getQueue, clearQueue } =
    useToast();

  ...
}

Targeting a Specific Toaster

If you have multiple toasters, you can invoke useToast with the toaster's id to target a specific toaster. Then, all the actions will called against that toaster.

const { notify } = useToast("toaster-1");

To target a different toaster in the same file, you can alias the methods:

const { notify } = useToast("toaster-1");
const { notify: notify2 } = useToast("toaster-2");

notify("Hello from toaster 1");
notify2("Hello from toaster 2");

Alternatively, you can store the result of useToast() in variables and call them separately:

const toaster1 = useToast("toaster-1");
const toaster2 = useToast("toaster-2");

toaster1.notify("Hello from toaster 1");
toaster2.notify("Hello from toaster 2");

If you don't want to target a specific toaster by calling useToast with a toasterId, you can provide the toasterId in the action's options.

notify("Hello, world!", { toasterId: "toaster-1" });
update({ toasterId: "toaster-1", id: "toastId", content: "Updated content" });

Available Actions

The useToast() function returns an object containing various toast actions:

  • notify - Creates a new toast with an optional configuration.
  • update - Updates an existing toast with new content or styling.
  • dismiss - Dismisses a specific toast by ID or all toasts if no ID is provided.
  • remove - Immediately removes a toast without animations.
  • promise - Displays a loading toast that updates based on promise resolution.
  • getQueue - Returns the current queue of toasts.
  • clearQueue - Clears all toasts in the queue.

notify()

The notify function is the primary way to trigger toasts in Solid Notifications. It allows you to display messages with optional configurations, such as assigning an ID, targeting a specific toaster, and customizing the toast appearance.

It takes two arguments: content and options and returns an object with the toast's ID, a reference to the toast element, and a progress control object.

notify: (content?: ToastContent, options?: ToastOptions) => {
  id: string;
  ref: HTMLElement | null;
  progressControls: ProgressControls;
};

Basic usage

The simplest way to use notify is by calling it with a message:

notify("Hello, world!");

To target a specific toaster, you can pass the toasterId in the options object:

notify("Hello, world!", { toasterId: "toaster-1" });

Content

The content is the first argument of the notify function. It can be a string, a JSX element, or a function that returns a string or JSX element.

  • String

    When passing a string signal, for it to be reactive, it should be passed without invoking it:

    const [text, setText] = createSignal("Hello, world!");
    
    notify(text);
  • JSX Element

    You can pass a JSX element directly to notify, allowing you to display fully custom-styled toasts using SolidJS components.

    notify(<div>Hello, world!</div>);
  • Function

    Passing a function as the content gives you access to the toast instance, allowing dynamic rendering based on its properties like id and progress. This is useful for more advanced toasts, such as loading indicators or interactive toasts.

    notify((toast) => (
      <div>
        <h1>{toast.id}</h1>
        <p>Current progress: {toast.progressManager.progress()}</p>
      </div>
    ));

Options

The second argument of notify is an options object that allows you to customize the behavior and appearance of the toast.

The options object accepts all the toastConfig properties and the other config properties except content (which is passed as the first argument).

notify("Hello, world!", { duration: 5000, class: "bg-blue-500", type: "info" });

Return value

The notify function returns an object with the following properties:

  • id - The unique identifier of the toast.
  • ref - A reference to the toast element.
  • progressControls - A progress control object that allows you to manage the toast's duration and progress bar.

You can provide your own toast id or let the library generate one for you.

notify("Hello, world!", { id: "custom-id" });

// or

const { id } = notify("Hello, world!");

The ref is part of the object returned by the notify function and provides a reference to the toast element itself. This can be useful if you need to directly interact with the DOM element

const { ref } = notify("Hello, world!");

ref.style.backgroundColor = "green";

The progressControls object contains the methods play, pause and reset, and the progress signal, allowing you to control the toast's duration and hook into the current progress.

const { progressControls } = notify(
  <div>
    <h1>Hello, world!</h1>
    <p>Current progress: {progressControls.progress()}</p>

    <button onClick={progressControls.play}>Play</button>
    <button onClick={progressControls.pause}>Pause</button>
    <button onClick={progressControls.reset}>Reset</button>
  </div>,
);

update()

The update function allows you to modify an existing toast's content or appearance. It takes one argument; an object containing toastConfig and other config properties.

  update: (options: ToastOptionsUpdate) =>
    | {
        id: string | undefined;
        ref: HTMLElement | null;
        progressControls: ProgressControls;
      }
    | undefined;
};
const { id } = notify("Hello, world!");

update({ id, content: "Updated content", duration: 10000 });

How It Works

The update function is designed to handle several scenarios, depending on the arguments provided:

  1. Update a specific toast:

    update({ id: "toastId", content: "Updated content", duration: 10000 });
  2. Update a specific toast in a specific toaster:

    update({
      id: "toastId",
      toasterId: "toaster-1",
      content: "Updated content",
      duration: 10000,
    });
  3. Update all toasts in a specific toaster:

    update({
      toasterId: "toaster-1",
      content: "Updated content",
      duration: 10000,
    });
  4. Update all toasts in all toasters:

    update({ content: "Updated content", duration: 10000 });

Options

The update function takes an object containing toastConfig and other config properties.

Return value

The update function returns the same object as the notify function, with the same properties.

dismiss()

The dismiss function allows you to remove a specific toast by ID or all toasts if no ID is provided. The exit animation and exit callback will be triggered.

  dismiss: (options?: {
    id?: string;
    toasterId?: string;
    reason?: string;
    keepQueued?: boolean;
  }) => void;

Options

The dismiss function accepts an optional options object with the following properties:

  • id: The unique identifier of the toast to dismiss. If provided, only the specified toast will be dismissed.
  • toasterId: The identifier of the toaster where the toast resides. If provided, the function will dismiss toasts only in the specified toaster.
  • keepQueued: A boolean flag that determines whether queued toasts should be preserved. If true, only rendered toasts will be dismissed.
  • reason: A string or custom value that can be used to track why a toast was dismissed (e.g., "user_action"). This value will be passed to the toast's exitCallback callback.

If no arguments are provided, the function will dismiss all toasts across all toasters.

How it Works

Here’s an example of how you might use the dismiss function in practice:

  1. Dismiss all toasts across all toasters:

    dismiss();
  2. Dismiss all rendered toasts across all toasters, keeping queued toasts:

    dismiss({ keepQueued: true });
  3. Dismiss a specific toast in a specific toaster:

    dismiss({ id: "toastId", toasterId: "toaster-1" });
  4. Dismiss all toasts in a specific toaster:

    dismiss({ toasterId: "toaster-1" });
  5. Dismiss all rendered toasts in a specific toaster, keeping queued toasts:

    dismiss({ toasterId: "toaster-1", keepQueued: true });

Providing a reason for dismissal

You can provide a reason for dismissing a toast by passing a reason property in the options object. This can be useful for tracking why a toast was dismissed, such as when a user manually closes a toast.

dismiss({ id: "toastId", reason: "user_action" });

And then in the toast's exitCallback callback:

notify("Hello, world!", {
  exitCallback: (reason) => {
    console.log(`Toast dismissed due to: ${reason}`);
  },
});

If no reason was provided, the reason argument will be generated by the library. If the toast was dismissed by the user, the reason will be true, otherwise it will be false.

notify("Hello, world!", {
  exitCallback: (dismissedByUser) => {
    console.log(`Toast dismissed by user? ${dismissedByUser}`);
  },
});

remove()

The remove function allows you to immediately remove a toast without triggering the exit animation and without running the exitCallback.

  remove: (options?: {
    id?: string;
    toasterId?: string;
    keepQueued?: boolean;
  }) => void;

Options

The remove function accepts the same arguments as the dismiss function except for the reason property.

How it Works

The remove function can be called the same way as the dismiss function, such as;

  1. Remove all toasts across all toasters:

    remove();
  2. Remove all rendered toasts across all toasters, keeping queued toasts:

    remove({ keepQueued: true });
  3. Remove a specific toast in a specific toaster:

    remove({ id: "toastId", toasterId: "toaster-1" });
  4. Remove all toasts in a specific toaster:

    remove({ toasterId: "toaster-1" });
  5. Remove all rendered toasts in a specific toaster, keeping queued toasts:

    remove({ toasterId: "toaster-1", keepQueued: true });

promise()

The promise function is a utility that simplifies handling async operations by displaying different toast states for pending, success, and error outcomes.

promise: <T>(
    promise: Promise<T>,
    messages: ToastPromiseMessages,
    options?: ToastOptions,
  ) => Promise<T>;

interface ToastPromiseMessages {
    pending: string | JSX.Element;
    success: string | JSX.Element | ((data: any) => string | JSX.Element);
    error: string | JSX.Element | ((error: any) => string | JSX.Element);
  }

How it Works

The promise function takes three arguments: - A promise. - An object containing messages for the pending, success, and error states. - An optional options object that allows you to customize the toast appearance and behavior.

const fetchData = () =>
  new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5
        ? resolve("Data loaded successfully!")
        : reject("Failed to fetch data.");
    }, 2000);
  });

try {
  const data = await promise(
    fetchData(),
    {
      pending: "Fetching data...",
      success: (data) => `✅ Success: ${data}`,
      error: (error) => `❌ Error: ${error}`,
    },
    { duration: 5000 },
  );

  console.log("Resolved data:", data);
} catch (error) {
  console.error("Caught error:", error);
}

Or you can directly manage the returned data and error in the promise messages:

const [data, setData] = createSignal(null);

const fetchData = () =>
  new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      Math.random() > 0.5
        ? resolve("Data loaded successfully!")
        : reject("Failed to fetch data.");
    }, 2000);
  });

promise(fetchData(), {
  pending: "Fetching data...",
  success: (data) => {
    setData(data); // Manage how you want to use the resolved data here
    return `✅ Promise resolved with data: ${data}`;
  },
  error: (error) => {
    setError(error); // Manage the error here
    return `❌ Promise rejected with error: ${error}`;
  },
});

Messages

The messages object contains three properties:

  • pending - The message to display while the promise is pending.
  • success - The message to display when the promise resolves successfully. This can be a string, JSX element, or a function that returns a string or JSX element. The function receives the resolved data as an argument.
  • error - The message to display when the promise is rejected. This can be a string, JSX element, or a function that returns a string or JSX element. The function receives the error as an argument.

Return value

The promise function returns a promise that resolves to the data returned by the original promise. This allows you to chain additional actions after the toast is dismissed.

getQueue()

The getQueue function returns an array of all toasts currently in the queue.

getQueue: (toasterId?: string) => Toast[];

How it Works

The getQueue function can be called with an optional toasterId argument to target a specific toaster. If no toasterId is provided, the function will return all queued toasts across all toasters.

const queue = getQueue();
// or
const queue = getQueue("toaster-1");

To show a number of toasts currently in the queue, you can use the length property of the returned array:

const { getQueue } = useToast();

return <div>There are currently {getQueue().length} toasts in the queue </div>;

clearQueue()

The clearQueue function removes currently queued toasts.

clearQueue: (toasterId?: string) => void;

How it Works

The clearQueue function can be called with an optional toasterId argument to target a specific toaster. If no toasterId is provided, the function will clear the queue for all toasters.

clearQueue();
// or
clearQueue("toaster-1");

© Copyright 2025 Solid Notifications

GitHub