useToast
Hooks

useToast

Pushes and dismisses toasts from anywhere under a ToastProvider.

Signature

toast is callable, and also carries ok, warn, and err shorthands for the toned variants. Each call returns the new toast's id, which you can pass to dismiss to close that one early.

SignatureTypeScript
function useToast(): {
  toast: {
    (options: ToastOptions | string): string;
    ok: (
      children: ReactNode,
      options?: Omit<ToastOptions, "children" | "tone">,
    ) => string;
    warn: (
      children: ReactNode,
      options?: Omit<ToastOptions, "children" | "tone">,
    ) => string;
    err: (
      children: ReactNode,
      options?: Omit<ToastOptions, "children" | "tone">,
    ) => string;
  };
  /** Omit the id to dismiss everything. */
  dismiss: (id?: string) => void;
  toasts: ToastRecord[];
};

Usage

ExampleTSX
import { useState } from "react";
import { ToastProvider, useToast } from "@solarius/onset";

type SaveProps = { save: () => Promise<void> };

function App({ save }: SaveProps) {
  return (
    <ToastProvider placement="bottom-right">
      <SaveButton save={save} />
    </ToastProvider>
  );
}

function SaveButton({ save }: SaveProps) {
  const { toast, dismiss } = useToast();
  const [saving, setSaving] = useState(false);

  return (
    <button
      disabled={saving}
      onClick={async () => {
        setSaving(true);
        const id = toast({ children: "Saving…", duration: 0 });
        try {
          await save();
          toast.ok("Saved");
        } catch {
          toast.err("Save failed. Try again.");
        } finally {
          dismiss(id);
          setSaving(false);
        }
      }}
    >
      Save
    </button>
  );
}