Upon clicking a button in my react Native app, I call two functions: getSolutionListFromDatabase
, which sets the state of the component to include this solution list, and then updateDatabaseSolutionList
, which adds an element to this list and pushes it back to Firebase. However, although the state of the application is being properly updated within the first function, within the second function the state is being logged as undefined, and my log statements for that function are being called before some statements in the first function. Are the functions operating asynchronously for some reason, and is this a feature of React native? If so, how can I prevent the second function from executing until the state has been set? Thanks.
onSubmitPressed: function() {
if (this.checkSolution) {
this.getSolutionListFromDatabase();
this.updateDatabaseSolutionList();
Alert.alert(
'Correct!',
"Woohoo!"
);
}
},
getSolutionListFromDatabase: function() {
var thisItemRef = itemsListRef.child(this.state.itemID);
thisItemRef.once('value', (snap) => {
var solutionList = snap.val();
this.setState({
solutionList: solutionList
});
console.log('solution is set as' + this.state.solutionList);
});
},
updateDatabaseSolutionList: function() {
var newSolutionList = [];
console.log('solutionList undefined here' + this.state.solutionList);
if (this.state.solutionList) {
newSolutionList = this.state.solutionList;
newSolutionList.push(this.props.itemID);
}
//then push new list to Firebase
},