chore: add client/src/hooks/use-toast.ts

This commit is contained in:
notshop 2026-04-26 16:35:03 +00:00
parent d05c981dae
commit 18cf3e8353

View file

@ -0,0 +1,40 @@
import { useState, useCallback } from "react";
type ToastVariant = "default" | "destructive" | "success";
interface Toast {
id: string;
title?: string;
description?: string;
variant?: ToastVariant;
}
let listeners: Array<(toasts: Toast[]) => void> = [];
let toastList: Toast[] = [];
function notify() {
listeners.forEach((l) => l([...toastList]));
}
export function toast(options: Omit<Toast, "id">) {
const id = Math.random().toString(36).slice(2);
toastList = [...toastList, { id, ...options }];
notify();
setTimeout(() => {
toastList = toastList.filter((t) => t.id !== id);
notify();
}, 4000);
}
export function useToast() {
const [toasts, setToasts] = useState<Toast[]>([]);
const subscribe = useCallback(() => {
listeners.push(setToasts);
return () => {
listeners = listeners.filter((l) => l !== setToasts);
};
}, []);
return { toasts, toast, subscribe };
}