- Added console logging to debug toast lifecycle - Improved toast ID generation with timestamp - Limited toasts to max 3 at a time - Toasts should now auto-dismiss after 3 seconds
60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
'use client'
|
|
|
|
import { createContext, useContext, useState, useCallback, ReactNode } from 'react'
|
|
import Toast, { ToastType } from './Toast'
|
|
|
|
interface ToastMessage {
|
|
id: string
|
|
message: string
|
|
type: ToastType
|
|
}
|
|
|
|
interface ToastContextType {
|
|
showToast: (message: string, type: ToastType) => void
|
|
}
|
|
|
|
const ToastContext = createContext<ToastContextType | undefined>(undefined)
|
|
|
|
export function useToast() {
|
|
const context = useContext(ToastContext)
|
|
if (!context) {
|
|
throw new Error('useToast must be used within ToastProvider')
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function ToastProvider({ children }: { children: ReactNode }) {
|
|
const [toasts, setToasts] = useState<ToastMessage[]>([])
|
|
|
|
const showToast = useCallback((message: string, type: ToastType) => {
|
|
const id = `${Date.now()}-${Math.random().toString(36).substring(7)}`
|
|
console.log('[ToastContainer] Showing toast:', id, message)
|
|
setToasts((prev) => {
|
|
// Limit to 3 toasts at a time
|
|
const newToasts = [...prev, { id, message, type }]
|
|
return newToasts.slice(-3)
|
|
})
|
|
}, [])
|
|
|
|
const removeToast = useCallback((id: string) => {
|
|
console.log('[ToastContainer] Removing toast:', id)
|
|
setToasts((prev) => prev.filter((toast) => toast.id !== id))
|
|
}, [])
|
|
|
|
return (
|
|
<ToastContext.Provider value={{ showToast }}>
|
|
{children}
|
|
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm w-full px-4 sm:px-0">
|
|
{toasts.map((toast) => (
|
|
<Toast
|
|
key={toast.id}
|
|
message={toast.message}
|
|
type={toast.type}
|
|
onClose={() => removeToast(toast.id)}
|
|
/>
|
|
))}
|
|
</div>
|
|
</ToastContext.Provider>
|
|
)
|
|
}
|