Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught (in promise) TypeError: querySnapshot.forEach is not a function React Native

I have a ‘users’ collection on Firebase. This collection has some fields in it which I’d like to render on the screen

I have a class Home which contains the following function:

const db = firebase.firestore();

    
export class Home extends Component {
  constructor(props) {
    super()
  }
  componentDidMount(){
     db.collection('/users')
     .doc(firebase.auth().currentUser.uid)
     .get()
     .then(querySnapshot => {
        querySnapshot.forEach(uid => {
        let data = uid.data();
           console.log(data);
        })
      })
  }
}

Without the .doc(firebase.auth().currentUser.uid), I get the all the fields of all the users on the screen but when I add this, to get the details per user, I encounter the error "Uncaught (in promise) TypeError: querySnapshot.forEach is not a function". Thanks in advance for the help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

You are using get() on a DocumentReference which returns a DocumentSnapshot that contains data of a single document only and there isn’t any forEach method present on it. So just using data() directly on the snapshot should do. Try refactoring the code as shown below:

componentDidMount() {
  db.collection('/users')
    .doc(firebase.auth().currentUser.uid)
    .get()
    .then((docSnapshot) => {
      console.log(docSnapshot.data())
    })
}

If you are trying to get all the documents from users collection, then use get() on CollectionReference (essentially remove the .doc(uid)) as shown below:

componentDidMount() {
  db.collection('/users')
    .get()
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        console.log(doc.data())
      })
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading