0

I'm trying to authenticate the user using the google. Everything is going fine. But when I try to console.log(this) inside of the onAuthStateChanged() is printing something like

Object { next: componentDidMount(user), error: noop(), complete: noop()
 }
​
complete: function noop()​
error: function noop()​
next: function componentDidMount(user)​
<prototype>: Object { … }

But if I console.log(this) outside of the onAuthStateChanged() its working fine with the information of the current class.

What I want is, I want to update the state information with the user details by using this this.setState() method. But this.setState() method is not working inside of the onAuthStateChanged().

How can I do it?

Here is my code

componentDidMount =  ()=>{
    console.log(this)
     firebase.auth().onAuthStateChanged(function (user) {
      if (user) {
        console.log(this)
        console.log("userSignedIn")
      } else {
        console.log(" No user is signed in.");
      }
    });
  };
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

The problem is that this has a different meaning inside the callback, due to how you declare it.

The simplest fix is to use a fat arrow to declare the callback, same as you do elsewhere:

componentDidMount =  ()=>{
  console.log(this)
  firebase.auth().onAuthStateChanged((user) => { // 
  if (user) {
    console.log(this)
    console.log("userSignedIn")
  } else {
    console.log(" No user is signed in.");
  }
});

This is an incredibly common problem, so I recommend reading more on it here: How to access the correct `this` inside a callback?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807