Although there is efficiency in the Firestore database, in the example below, when the chat application performs onSnapshot, querySnapshot returns empty.
useEffect(() => {
if (!token || !eventId) return; // Add eventId check
fetchEventDetails();
console.log("Fetching messages for event:", eventId);
const messagesRef = collection(db, "events", eventId, "chats", "default", "messages");
const messagesQuery = query(messagesRef, orderBy("timestamp", "desc"));
const unsubscribe = onSnapshot(messagesQuery, querySnapshot => {
// Add a log at the start of the callback to verify it runs.
console.log("onSnapshot callback triggered");
// Check if the snapshot is empty
if (querySnapshot.empty) {
console.log("No documents found in messages");
} else {
console.log("Snapshot data:", querySnapshot.docs.map(doc => doc.data())); // Log the data
}
setMessages(
querySnapshot.docs.map(doc => ({
message_id: doc.ref.id,
user_id: doc.data().user_id,
username: doc.data().username,
content: doc.data().content,
timestamp: doc.data().timestamp ? doc.data().timestamp.toDate() : new Date(),
fileUrl: doc.data().fileUrl || "",
}))
);
});
return () => unsubscribe();
}, [token, eventId]);
Firebase is working because I can make auth when I log in. I have taking log as:
(NOBRIDGE) LOG Fetching messages for event: 4
(NOBRIDGE) LOG onSnapshot callback triggered
(NOBRIDGE) LOG No documents found in messages
How can I solve this?
I made many console logs. Even though I tried to access a single document directly, I still could not access it.