diff --git a/src/components/providers/header-provider.tsx b/src/components/providers/header-provider.tsx index 214f39d..0e66aa5 100644 --- a/src/components/providers/header-provider.tsx +++ b/src/components/providers/header-provider.tsx @@ -129,6 +129,8 @@ export function HeaderProvider({ children }: { children: React.ReactNode }) { } }; + const fetchBothCounts = () => { fetchCount(); fetchMessageCount(); }; + fetchCount(); fetchMessageCount(); const interval = setInterval(fetchCount, 30000); @@ -136,18 +138,28 @@ export function HeaderProvider({ children }: { children: React.ReactNode }) { const handleNotification = () => fetchCount(); window.addEventListener('notification-received', handleNotification); + // Instantly refresh both counts when messages are read + // (dispatched by useMessaging when user views a conversation) + window.addEventListener('messages-read', fetchBothCounts); + // Listen to socket events for immediate notification count refresh const unsubConnectionReq = socketService.onConnectionRequest(() => fetchCount()); const unsubConnectionRes = socketService.onConnectionResponse(() => fetchCount()); const unsubNewMessage = socketService.onNewMessage(() => { fetchCount(); fetchMessageCount(); }); + // Listen to messages_read socket event (when other party reads, or when + // mark_read response comes back) to keep counts synchronized + const unsubMessagesRead = socketService.onMessagesRead(() => fetchBothCounts()); + return () => { clearInterval(interval); clearInterval(messageInterval); window.removeEventListener('notification-received', handleNotification); + window.removeEventListener('messages-read', fetchBothCounts); unsubConnectionReq(); unsubConnectionRes(); unsubNewMessage(); + unsubMessagesRead(); }; }, [status]);