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