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.
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
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>
);
}