I want to show a badge, if the actual user has a unread message. It works if the first user write a message to the second user. But if the second user writes a message in the same time to the other user the badge comes but it is only two seconds.
The messageRead Function is triggert in the toDetail Function, which is a function if the user tabs on the Chat.
async MessageIsRead(uid: any){
const db = getFirestore();
const messagesColRef = collection(db, "messages");
const currentUserUid = (await this.fireAuth.currentUser)?.uid;
onSnapshot(messagesColRef, async (messagesSnap) => {
const messages = messagesSnap.docs.map((message) => message.data());
for (const message of messages) {
if (message['from'] == uid || message['from'] == currentUserUid) {
const messageRef = this.firestore.doc(`messages/${message['id']}`);
await messageRef.update({ read: true });
}else {
break;
}
}
});
}
To show the Badge on the User I have following code:
this.items = filteredUsers.map((user: any) => {
const conversationMessages = filteredMessages.filter((message) => message['from'] === user.uid );
this.unreadCount = conversationMessages.reduce((acc, message) => {
if (!message['read']) {
const isUnread = conversationMessages.every(otherMessage => {
if (message['createdAt'] < otherMessage['createdAt']) {
return false;
}
return true;
});
if (isUnread) {
acc++;
}
}
return acc;
}, 0);
return {
name: user['name'],
image: user['image'],
uid: user['uid'],
read: this.unreadCount > 0
};
});
});
});
} catch (error) {
console.error(error);
}
}
And then the HTML:
<ion-badge color="danger" *ngIf="item.read"> </ion-badge>
How can I make it, that the badge is only shown if the other user tabs on the chat?
The whole code is on Github: GitHub - mark-baumann/drink-together
My database:
I expected it would only show the badge if the actual user tabs on the chat and it won´t be gone after seconds.