How do I get document and nested collection in a document in a Cloud Firestore collection using Version 9 of the Modular Web SDK?

Viewed 734

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])

3 Answers

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:

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])

This is just for others....

V8:

export const fetchAccountAssets = (userID, accountID) => db()
  .collection('Accounts')
  .doc(userID)
  .collection('Assets')
  .get()
  .then((querySnapshot) => querySnapshot);

V9:

export const fetchAccountAssets = async (userID, accountID) => {
  return await getDocs(collection(db, 'Accounts', userID, 'Assets'));
}

I dont think I need to await here but oh well..

Related