Files
uuid-playground/src/hooks/useToast.ts
T
2025-11-12 19:57:52 +08:00

29 lines
722 B
TypeScript

import { useCallback, useState } from 'react'
export interface Toast {
id: string
message: string
type: 'success' | 'error' | 'info'
}
export function useToast() {
const [toasts, setToasts] = useState<Toast[]>([])
const showToast = useCallback((message: string, type: Toast['type'] = 'success') => {
const id = Math.random().toString(36).substring(2, 9)
const toast: Toast = { id, message, type }
setToasts(prev => [...prev, toast])
setTimeout(() => {
setToasts(prev => prev.filter(t => t.id !== id))
}, 3000)
}, [])
const removeToast = useCallback((id: string) => {
setToasts(prev => prev.filter(t => t.id !== id))
}, [])
return { toasts, showToast, removeToast }
}