# useToastManager

Adds, updates and closes toasts in the nearest toast provider, which `MosaicProvider` and profile dialogs mount. A toast is a stacked card in the viewport (`cl-toast-root`), or a small label next to an element when `positionerProps.anchor` is set. `type` of `success`, `error` or `loading` shows an icon or spinner. Toasts close after 5 seconds and at most 3 stack.

## Use for

- a confirmation after an action succeeds, such as invitations sent
- a message that tracks a promise from loading to success or error
- a short label next to a button, such as Copied

## Practices

- Do: Call it in the controller and add the toast when the action resolves.
- Do: Pass the same `id` to `add` to refresh an open toast instead of stacking a copy.
- Don't: Show an error that belongs on a form or row in a toast. Use the owners in "Reuse before you write" instead.

## Returns

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `toasts` | `ToastObject[]` |  | The current toasts, newest first. |
| `add` | `(options: ToastOptions) => string` |  | Shows a toast from `{ label, description, type, timeout, priority, id, positionerProps }` and returns its id. `timeout: 0` keeps it until closed. |
| `close` | `(id?: string) => void` |  | Closes the toast with this id, or every toast without one. |
| `update` | `(id: string, options: ToastUpdateOptions \| ((toast: ToastObject) => ToastUpdateOptions)) => void` |  | Merges new options into a toast, or a function of the current toast. |
| `promise` | `<Value>(promise: Promise<Value>, options: ToastPromiseOptions<Value>) => Promise<Value>` |  | Shows `loading` until the promise settles, then `success` or `error`, each a label, options or a function of the result. Returns the promise. |

## Examples

### After an action

```tsx
const toast = useToastManager();
toast.add({ type: 'success', label: m.sent });
```

### Track a promise

```tsx
await toast.promise(save(), { loading: m.saving, success: m.saved, error: m.failed }).catch(() => {});
```

## Related

- [CopyButton](/docs/components/copy-button.md)
- `MosaicProvider`
