Reputation: 285
I am trying to set the state inside of a firebase snapshot function but I am getting an Cannot read property 'setState' of null
error. I am not sure how to make it work.
This is my code:
componentDidMount = () => {
const dataGoalRef = dbRef.child('goals/'+this.state.uid);
dataGoalRef.child("mainGoal").on("value", function(mainGoalKeySnapshot) {
var favoriteMainGoal = mainGoalKeySnapshot.val();
console.log(favoriteMainGoal);
var queryRef = dataGoalRef.orderByKey().equalTo(favoriteMainGoal);
queryRef.on("value", snap => {
this.setState({
dataGoal: snap.val(),
});
});
});
}
How can I do so?
Upvotes: 1
Views: 304
Reputation: 2067
Try by using arrow function instead of normal function declaration for callback which you have passed in dataGoalRef.child("mainGoal").on("value", function(mainGoalKeySnapshot){})
updated code
dataGoalRef.child("mainGoal").on("value", (mainGoalKeySnapshot) => {
....
....
});
Upvotes: 0
Reputation: 285
I've just figured it out. I wasn't binding the first method. So the solution is:
componentDidMount = () => {
const dataGoalRef = dbRef.child('goals/'+this.state.uid);
dataGoalRef.child("mainGoal").on("value", (mainGoalKeySnapshot) => {
var favoriteMainGoal = mainGoalKeySnapshot.val();
console.log(favoriteMainGoal);
var queryRef = dataGoalRef.orderByKey().equalTo(favoriteMainGoal);
queryRef.on("value", snap => {
this.setState({
dataGoal: snap.val(),
});
});
});
}
Upvotes: 1