Home > other >  How to get specific data from all documents from a collection in firebase?
How to get specific data from all documents from a collection in firebase?

Time:09-16

Platform: React Native (Expo)

So I'm trying to get two values (dotCoins and name) from my firebase db and I can't figure out how to go about it. Here's my firebase structure: Firebase sturcture

This is what I currently have in place:

// Calling function when screen loads
  componentDidMount() {
    this.getDotCoins();
    this.getUserData();
  }

// Calling function when it updates
  componentDidUpdate() {
    this.getDotCoins();
    this.getUserData();
  }

// The function
  getUserData = async () => {
    const querySnapshot = await getDocs(collection(db, "users"));
    const tempDoc = [];
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });
    console.log(tempDoc);
  };

Both the console.log() prints nothing, and my console remains absolutely empty. I can't find where I'm going wrong since I don't receive any errors too. (I have all packages installed correctly and all functions imported too)

CodePudding user response:

You are not pushing any document data to tempDoc so it'll always be empty. Try refactoring the code as shown below:

getUserData = async () => {
  const querySnapshot = await getDocs(collection(db, "users"));

  const tempDoc = querySnapshot.docs.map((d) => ({
    id: d.id,
    ...d.data()
  }));

  console.log(tempDoc);
};

CodePudding user response:

const q = query(collection(db, "users"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
            querySnapshot.forEach((doc) => {
                     console.log(doc.data())
                })
            });
        });


        return unsubscribe;
  • Related