Fix unread divider: update sessionUnreadRef when messages are marked as read
This commit is contained in:
@@ -187,12 +187,31 @@ export default function ChatView({ onStartCall, onStartGroupCall }: { onStartCal
|
||||
// Refs and logic for tracking session's first unread message to show the divider exactly once per load
|
||||
const sessionUnreadRef = useRef<{ chatId: string, msgId: string | null }>({ chatId: '', msgId: null });
|
||||
|
||||
if (activeChat && activeChat !== sessionUnreadRef.current.chatId && !isLoadingMessages) {
|
||||
const firstUnreadMsg = chatMessages.find(
|
||||
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
|
||||
);
|
||||
sessionUnreadRef.current = { chatId: activeChat, msgId: firstUnreadMsg ? firstUnreadMsg.id : null };
|
||||
}
|
||||
// Update sessionUnreadRef when chat changes OR when messages are marked as read
|
||||
useEffect(() => {
|
||||
if (!activeChat || isLoadingMessages) return;
|
||||
|
||||
// Reset on chat change
|
||||
if (activeChat !== sessionUnreadRef.current.chatId) {
|
||||
const firstUnreadMsg = chatMessages.find(
|
||||
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
|
||||
);
|
||||
sessionUnreadRef.current = { chatId: activeChat, msgId: firstUnreadMsg ? firstUnreadMsg.id : null };
|
||||
} else {
|
||||
// Update if the first unread message was read (msgId no longer exists in unread list)
|
||||
const firstUnreadMsg = chatMessages.find(
|
||||
(m) => m.senderId !== user?.id && !m.readBy?.some((r) => r.userId === user?.id)
|
||||
);
|
||||
if (sessionUnreadRef.current.msgId && !firstUnreadMsg) {
|
||||
// All messages are now read
|
||||
sessionUnreadRef.current.msgId = null;
|
||||
} else if (firstUnreadMsg && sessionUnreadRef.current.msgId !== firstUnreadMsg.id) {
|
||||
// First unread changed (some messages were read)
|
||||
sessionUnreadRef.current.msgId = firstUnreadMsg.id;
|
||||
}
|
||||
}
|
||||
}, [activeChat, chatMessages, user?.id, isLoadingMessages]);
|
||||
|
||||
const firstUnreadId = activeChat === sessionUnreadRef.current.chatId ? sessionUnreadRef.current.msgId : null;
|
||||
const initialScrollChatId = useRef<string | null>(null);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user