I'm trying to update the state of a React Component, based on data retrieved through an API. However, I am unable to use the setState function from within the promise, as React Native always returns the following error "Type Error: _this2.setState is not a function". Here is how I am trying to achieve the following:
let foodList = [];
Firebase.auth().onAuthStateChanged(function(user) {
if (user) {
Firebase
.firestore()
.collection(`/userProfiles/${user.uid}/foodList`)
.get()
.then(foodListSnapshot => {
foodListSnapshot.forEach(snap => {
foodList.push({
foodName: snap.data().name,
mealConsumed: snap.data().meal,
estimatedCalories: snap.data().calories,
dateConsumed: snap.data().date
});
});
}).then((foodList) => {
this.setState({data: foodList});
}).catch(error => console.log(error));
} else {
Alert.alert('User not signed in');
}
});
My goal is to have the component re-render, once the state's data field has been updated.
I have tried also using bind.this
however as I'm quite new to React Native, I have been unsuccessful in figuring it out so far. If someone could help me out with this, I would be extremely appreciative! :)