3

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 Answers3

2

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:

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • First, Thanks a lot for your help. Still not working though, it says : Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf') index.esm2017.js:1030 –  Sep 26 '21 at 19:51
  • I added roomId between [] in useEffect and still the same error –  Sep 26 '21 at 20:03
2

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])
Mrkouhadi
  • 446
  • 5
  • 14
0

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..

Denis
  • 570
  • 9
  • 23