I am looking to retrieve my sub collection "messages" within the "channels" collection and display them on my chat page. I tried different tactics like useEffect but with no result.
How would I change this line of code from v8 to v9?:
const [messages] = useCollection(
channelId &&
db
.doc(channelId)
.collection("messages")
.orderBy("timestamp", "asc")
);
Message display section:
<div>
{messages?.docs.map((doc) => {
const { message, timestamp, name, photoURL, email } = doc.data();
return (
<Message
key={doc.id}
id={doc.id}
message={message}
timestamp={timestamp}
name={name}
email={email}
photoURL={photoURL}
/>
);
})}
</div>
I am able to send message to firestore, but getting it to display has been a problem. Everytime I map through messages, my app turn blank.
CodePudding user response:
If you would like to retrieve the data once you do not need a useEffect hook.
Perform the query as follows:
const collectionRef = query(
collection(db, `channels/${channelId}/messages`),
orderBy("timestamp", "asc"));
const messageDocs = await collectionRef.get() // this is only the docs
// to get the doc data you will need to map each doc to its data
const messageDocsData = messageDocs.map((doc) => doc.data())
If you want your data to change on the UI as the database is updated you will need useEffect:
const [messageDocsData, setMessageDocsData] = useState([]);
const collectionRef = query(
collection(db, `channels/${channelId}/messages`),
orderBy("timestamp", "asc"));
useEffect(() => {
const unsubscribe = onSnapshot(collectionRef, (querySnapshot) =>
setMessageDocsData(querySnapshot.docs.map((doc) => doc.data()))
);
return () => unsubscribe();
}, []);
// messageDocsData will now always have the latest snapshot of the documents