skip to Main Content

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)

2

Answers


  1. 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);
    };
    
    Login or Signup to reply.
  2. const q = query(collection(db, "users"));
    const unsubscribe = onSnapshot(q, (querySnapshot) => {
                querySnapshot.forEach((doc) => {
                         console.log(doc.data())
                    })
                });
            });
    
    
            return unsubscribe;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search