feat: add event listeners to synchronize notification and message counts upon read events
This commit is contained in:
@@ -129,6 +129,8 @@ export function HeaderProvider({ children }: { children: React.ReactNode }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const fetchBothCounts = () => { fetchCount(); fetchMessageCount(); };
|
||||||
|
|
||||||
fetchCount();
|
fetchCount();
|
||||||
fetchMessageCount();
|
fetchMessageCount();
|
||||||
const interval = setInterval(fetchCount, 30000);
|
const interval = setInterval(fetchCount, 30000);
|
||||||
@@ -136,18 +138,28 @@ export function HeaderProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const handleNotification = () => fetchCount();
|
const handleNotification = () => fetchCount();
|
||||||
window.addEventListener('notification-received', handleNotification);
|
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
|
// Listen to socket events for immediate notification count refresh
|
||||||
const unsubConnectionReq = socketService.onConnectionRequest(() => fetchCount());
|
const unsubConnectionReq = socketService.onConnectionRequest(() => fetchCount());
|
||||||
const unsubConnectionRes = socketService.onConnectionResponse(() => fetchCount());
|
const unsubConnectionRes = socketService.onConnectionResponse(() => fetchCount());
|
||||||
const unsubNewMessage = socketService.onNewMessage(() => { fetchCount(); fetchMessageCount(); });
|
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 () => {
|
return () => {
|
||||||
clearInterval(interval);
|
clearInterval(interval);
|
||||||
clearInterval(messageInterval);
|
clearInterval(messageInterval);
|
||||||
window.removeEventListener('notification-received', handleNotification);
|
window.removeEventListener('notification-received', handleNotification);
|
||||||
|
window.removeEventListener('messages-read', fetchBothCounts);
|
||||||
unsubConnectionReq();
|
unsubConnectionReq();
|
||||||
unsubConnectionRes();
|
unsubConnectionRes();
|
||||||
unsubNewMessage();
|
unsubNewMessage();
|
||||||
|
unsubMessagesRead();
|
||||||
};
|
};
|
||||||
}, [status]);
|
}, [status]);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user