File size: 1,346 Bytes
c0e8080 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
typescript
import React, { createContext, useContext, useState, ReactNode } from 'react'
export type ToastType = 'success' | 'error' | 'warning' | 'info'
interface Toast {
id: string
type: ToastType
title: string
message?: string
}
interface ToastContextType {
toasts: Toast[]
addToast: (toast: Omit<Toast, 'id'>) => void
removeToast: (id: string) => void
}
const ToastContext = createContext<ToastContextType | undefined>(undefined)
export const useToast = () => {
const context = useContext(ToastContext)
if (context === undefined) {
throw new Error('useToast must be used within a ToastProvider')
}
return context
}
interface ToastProviderProps {
children: ReactNode
}
export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
const [toasts, setToasts] = useState<Toast[]>([])
const addToast = (toast: Omit<Toast, 'id'>) => {
const id = Math.random().toString(36).substr(2, 9)
setToasts(prev => [...prev, { ...toast, id }])
// Auto remove after 5 seconds
setTimeout(() => {
removeToast(id)
}, 5000)
}
const removeToast = (id: string) => {
setToasts(prev => prev.filter(toast => toast.id !== id))
}
return (
<ToastContext.Provider value={{ toasts, addToast, removeToast }}>
{children}
</ToastContext.Provider>
)
}
</html> |