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.
>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())
})
})
}
