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 useEffect
s. 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
Xcode 5 Crashes -- Xcode Quit Unexpectedly
Return from Initializer Without Initializing All Stored Properties
How to Programmatically Find Swift's Version
Convert String to Nsurl Is Return Nil in Swift
Wrong Frame Size in Viewdidload
How to Fix Failed to Fetch Default Token Error
Why Is Uiscrollview Leaving Space on Top and Does Not Scroll to the Bottom
Swift: How to Execute an Action When Uitabbaritem Is Pressed
Facebook Sdk 3.1 for iOS - Runs on iOS6, But Crashes on iOS 5.X
How to Get Available Wifi Network Name in iOS Using Swift
Appdelegate and Scenedelegate When Supporting iOS 12 and 13
Working with Live Photos in Playground
Calculate Total Traveled Distance iOS Swift
Dynamic Height for Static Table Cells with Wrapping Labels
How to Insert 40000 Records Fast into an SQLite Database in an iPad