Reputation: 157
I have a Firestore listener to grab chat messages for which I use a limit of 10. Everything works well on first load. However, when there are 10 messages and the limit is reached, the chat does not accept new messages. It is as if the limit function accepts the first 10 messages and then will not take any more when I need it to be updated with every new message. Here's the listener code:
startChat() {
document.getElementById("myForm").style.display = "block";
const ref = firebase
.firestore()
.collection("Chats")
.doc(this.state.uid)
.collection("Messages");
const query = ref.orderBy("timestamp", "asc").limit(10);
this.unsubFromMessages = query.onSnapshot(
(snapshot) => {
console.log(
snapshot.docs.map((doc) => {
return doc.data();
})
);
if (snapshot.empty) {
console.log("No matching documents.");
firebase
.firestore()
.collection("Chats")
.doc(this.state.uid)
.set({
name: this.state.displayName,
uid: this.state.uid,
email: this.state.email,
})
.then(console.log("info saved"))
.catch((error) => {
console.log("Error saving info to document: ", error);
});
}
snapshot.docChanges().forEach((change) => {
if (change.type === "removed") {
console.log(change.doc.data().content);
} else if (change.type === "added") {
this.setState((state) => {
const messages = [
...state.messages,
{ id: change.doc.id, body: change.doc.data() },
];
return {
messages,
};
});
setTimeout(this.scrollToBottom(), 2000);
}
});
},
(error) => {
console.log(error);
}
);
}
Does anyone know why this is happening and how to make the limit function accept new messages? Thanks.
Upvotes: 0
Views: 232
Reputation: 157
Nicholas's answer does, indeed, solve the issue. However, it does not solve the issue of messages loading in the wrong order when the chat is closed, then started and the previously entered messages are shown. One way to solve this issue is adding reverse() to docChanges() like this: snapshot.docChanges().reverse().forEach. Hope this might help someone. Happy coding, everyone. Stackoverflow rocks!
Upvotes: 0
Reputation: 85132
orderBy("timestamp", "asc")
With this order, you will be getting back the 10 oldest messages. New messages will have a higher timestamp, and so a new 11th message will not be part of the oldest 10.
If instead you want the 10 newest messages, use descending order:
orderBy("timestamp", "dsc")
Upvotes: 1