//Why this question isn't a duplicate of (How to access the correct `this` inside a callback?) : my question is a react-specific question and visitors might not mentally connect the dots between the issue raised in the above link and what I'm struggling with.
I'm trying to store the user data returned by Firebase auth's onAuthStateChanged function and store that data in state to work with it in my react app. In my app, I have the below listener:
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
var theUser;
if (user) {
console.log("user is logged in!");
theUser = user;
this.setState({
session: theUser
});
// User is signed in.
} else {
// No user is signed in.
console.log("user is not logged in!")
theUser = null;
}
}
}
But I get the error "TypeError: this.setState is not a function". I've tried binding "this" to componentDidMount to no avail.