Fix toast auto-dismiss issue by using ref for onClose callback

- Toast component now uses useRef to store onClose callback
- Prevents timer from resetting on parent re-renders
- Fixes issue where toasts wouldn't dismiss after adding items
This commit is contained in:
2025-12-07 01:06:03 +00:00
parent 737049dc69
commit 021bbf1335

View File

@@ -1,6 +1,6 @@
'use client'
import { useEffect } from 'react'
import { useEffect, useRef } from 'react'
import { CheckCircle, XCircle, AlertCircle, X } from 'lucide-react'
export type ToastType = 'success' | 'error' | 'info'
@@ -13,19 +13,26 @@ interface ToastProps {
}
export default function Toast({ message, type, onClose, duration = 3000 }: ToastProps) {
const onCloseRef = useRef(onClose)
// Keep the ref updated
useEffect(() => {
onCloseRef.current = onClose
}, [onClose])
useEffect(() => {
if (duration > 0) {
console.log(`[Toast] Setting timer for ${duration}ms`)
const timer = setTimeout(() => {
console.log('[Toast] Auto-dismissing')
onClose()
onCloseRef.current()
}, duration)
return () => {
console.log('[Toast] Clearing timer')
clearTimeout(timer)
}
}
}, [duration, onClose])
}, [duration])
const icons = {
success: <CheckCircle size={20} className="flex-shrink-0" />,