import { useCallback, useEffect, useRef, useState } from 'react'; export interface ToastItem { id: number; message: string; type: 'success' | 'error' | 'info'; } interface ToastProps { toasts: ToastItem[]; } export function Toast({ toasts }: ToastProps) { return (
{toasts.map(t => (
{t.type === 'success' ? '✓ ' : t.type === 'error' ? '✕ ' : 'ℹ '}{t.message}
))}
); } let _toastId = 0; export function useToast() { const [toasts, setToasts] = useState([]); const timerRef = useRef>>(new Map()); const showToast = useCallback((message: string, type: ToastItem['type'] = 'success', duration = 2500) => { const id = ++_toastId; setToasts(prev => [...prev, { id, message, type }]); const timer = setTimeout(() => { setToasts(prev => prev.filter(t => t.id !== id)); timerRef.current.delete(id); }, duration); timerRef.current.set(id, timer); }, []); useEffect(() => { const timers = timerRef.current; return () => { timers.forEach(t => clearTimeout(t)); }; }, []); return { toasts, showToast }; }