I am facing a challenge in updating the state of a React Component with data obtained from an API call. I encountered an issue where using the setState function within the promise resulted in an error "Type Error: _this2.setState is not a function" in React Native. The code snippet below demonstrates my approach:
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 objective is to trigger a re-render of the component once the 'data' field in its state has been updated.
Despite attempting to use bind.this
, as a beginner in React Native, I have struggled to resolve this issue on my own. Any assistance or guidance would be greatly appreciated! :)