I am having trouble retrieving all unread messages for the current user from Firebase. The issue arises when using onSnapshot()
as it initially fetches the required data but fails to do so when a new document is added, resulting in an error.
FirebaseError: Function Query.onSnapshot() requires between 1 and 4 arguments, but was called with 0 arguments.
This function serves as a helper to get the count of all unread messages for the current user.
async getUnseenMessagesCount() {
const collectionRef = (await firestore()).collection(this.collectionPath) //chats/${user_id+second_identifier/messages}
let allMessagesCount = 0
let currentUserReadMessagesCount = 0
try {
collectionRef.onSnapshot().then(snapshot => {
allMessagesCount = snapshot.docs.length
})
collectionRef
.where('seenBy', '==', '') // compare against empty string because seenBy is userId.
.onSnapshot()
.then(snapshot => {
currentUserReadMessagesCount = snapshot.docs.length
})
} catch (error) {
console.log(error)
}
console.log(allMessagesCount)
console.log(currentUserReadMessagesCount)
console.log(allMessagesCount - currentUserReadMessagesCount)
}
To find the total count of unread messages across all chats the user is involved in, I perform the following operation within my Vuex action triggered by auth state changes:
new UserChatsDB(newUser.id).readAll().then(snapshot => { //users/id/chats/{chat_id: user_id+second_identifier}
if (snapshot.length > 0) {
snapshot.forEach(element => {
console.log(element)
const count = new MessagesDB(
element.chat_id
).getUnseenMessagesCount()
console.log(count) //Returns pending Promise
})
}
})
What might be causing the aforementioned error? Is there a more effective approach to this problem? Please advise whether knowledge of the database structure would be helpful. Your assistance is greatly appreciated!