react-nativethisfacebook-loginfbsdk

cannot read "this" in react native function


I am trying to set the user data from facebook login and store it in a state but there is an error occurred.

Facebook Authentication

_fbAuth(){
  LoginManager.logInWithReadPermissions(['public_profile']).then(function(res){
    if(res.isCancelled){
      console.log('login cancelled.')
    } else {
      AccessToken.getCurrentAccessToken().then(tokenData => {
        if(tokenData) {
          const { accessToken, userID } = tokenData;
          fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + accessToken).then((response) => 
            response.json()).then((json) => {
              this.setState({ user_email: json.email })
            }).catch(() => {
              reject('ERROR GETTING DATA FROM FACEBOOK')
            }
          )
        }
      })
    }
  }, function(err){
    console.log(err)
  })
}

Registering the data into a state throwing this error :

[TypeError: undefined is not a function (evaluating '_this3.setState({ user_email: json.email })')]

How should I access this inside the fetch() response?


Solution

  • The reason is due to the fact that this has gotten lost due to the nested arrow functions. You define a variable to hold a reference to this and use that instead.

    You can solve it by doing the following inside your function

    _fbAuth = () => {
      const that = this;
      ...
      that.setState({ user_email: json.emal });
      ...
    }
    

    You should also make sure that you have bound your function by either making it an arrow function, or by binding it in the constructor.