Count Unseen Messages with Firebase in Swift

Update number of unread messages in Firebase using Swift

Refactor your CreateChatRoom func like this:

    let infoForCreator = ["userName": contactName, "newMessage" : 0]
let infoForContact = ["userName": creatorName, "newMessage" : 0]

And, try to change your AddNewMsgTick to use:

ref.observeSingleEvent

how to structure unseen count and messages for group chat firebase realtime database?

I typically track the key or timestamp of the last message each user has seen. From that you can then create a query that gets only messages from there on.

If you want a count of the unread message count for each user, you could store their "last seen key" in the database, and use that to determine the unseen message count for each of them by either running a query for each of them, or (better) by determining the oldest unseen, running a query for that, and then calculating the rest in code.

Of course you could also store the unseen message count for each user in the database, in which case I would use a Cloud Function that increments the counters on every message that is added, and decrements it whenever an (older) message is removed.

Count unread messages using firebase and react js

Split your code into two separate useEffects. Also, using SetNotifaction inside a loop will cause a lot of problems. I suggest using Array.filter instead.

const [notification,SetNotification] = useState(0)
const [messages,SetMessages] = useState([])

useEffect(() => {
const getMessages = async () => {
const data = await getDocs(lastMessageRef)
SetMessages(data.docs.map((doc) => ({...doc.data(), id:doc.id})))
};
getMessages();
}, [messages]);

useEffect(() => {
const unreadMessages = messages.filter(message => message.read === false)

SetNotification(unreadMessages.length)

}, [messages]);


Related Topics



Leave a reply



Submit