Reputation: 63
I am using React and getting data from my Firestore DB in my componentDidMount()
method. I have two then()
calls, one for when the data from the DB becomes available and I can save it, and the other for adjusting the state.
componentDidMount() {
db.collection("myCollection")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data().field1);
allData.push(doc.data());
})
})
.then(
console.log("Setting State"),
this.setState({
isLoaded: true,
items: allData
}))
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
However, when I run the site, it attempts to set the state (the second then()
statement) first when I don't want it to do that till after the DB data is saved. I'm not sure how to force the state change to happen after the DB data is saved.
Things I've tried:
1) Putting the state change directly after the the function code, within the first then(). This gives the error:
Error getting documents: TypeError: Cannot read property 'setState' of undefined
Upvotes: 0
Views: 54
Reputation: 1601
You've forgotten to wrap your set state and console log in another function. Without that you are passing two arguments to then, one is the result of console.log and the other is the result of this.setState. Those are synchronous calls the way you have written it.
Upvotes: 1