Home > other >  How do I get document and nested collection in a document in a Cloud Firestore collection using Vers
How do I get document and nested collection in a document in a Cloud Firestore collection using Vers

Time:09-27

I am following along with a tutorial in which using Firestore to retrieve data from a collection. there two major things: retrieve DOCUMENT and COLLECTION that's nested inside that DOCUMENT. My code down below is based on FireStore web v8, and I want to convert it to web version 9. I found it very complicated !

    useEffect(()=>{
        if(roomId){
            db.collection('rooms').doc(roomId).onSnapshot(snapshot => {
                setRoomName(snapshot.data().name);
            });

            db.collection('rooms').doc(roomId).collection("messages").orderBy("timestamp","asc").onSnapshot(snapshot => {
                setMessages(snapshot.docs.map(doc => doc.data()))
            });

        }
    },[roomId])

CodePudding user response:

This one should do the job !

    useEffect(() => {
        if(roomId){
            onSnapshot(doc(db, "rooms", roomId), (document) =>{ 
                setRoomName(document.data().name);
            });
            const msgColl = query(collection(db, "rooms", roomId, "messages"), orderBy("timestamp"));
            onSnapshot(msgColl, (querySnapshot) => {
                setMessages(querySnapshot.docs.map(msg => msg.data()))
            });
        }
    }, [roomId])

CodePudding user response:

Try this:

import { collection, query, where, doc, onSnapshot } from "firebase/firestore";

useEffect(() => {
  onSnapshot(doc(db, "rooms", roomId), (doc) => {
    setRoomName(doc.data().name)
  });

  const q = query(collection(db, "rooms", roomId, "messages"), orderBy("timestamps"));

  onSnapshot(q, (querySnapshot) => {
    setMessages(querySnapshot.docs.map(doc => doc.data()))
  });
}, [roomId])

Also checkout:

  • Related