Trying to update the react state within if statement.
When snapshot returns true -> switch state from true to false. When snapshot returns false -> switch state from false to true.
If i console.log(this.state.notification) above the if statement, everything is fine, when i log or want to edit inside the if statement i keep getting error: [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.state.notification')]
i tried to use bind but didn't work.
Help please!
state = {
darkMode: true,
notification: true
};
toggleNotification = async () => {
console.log(this.state.notification); // no error
const currentUserId = firebase.auth().currentUser.uid;
const ref = firebase.database().ref("users/" + currentUserId + "/notification");
ref.once("value").then(function(snapshot) {
if(snapshot){
this.setState({ notification: false }) // error
console.log(this.state.notification); // error
console.log('First check')
} else {
this.setState({ notification: true }) // error
console.log(this.state.notification); // error
console.log('Second check')
}
});
};