react-nativereact-navigationreact-native-fbsdk

The navigation not work in a function


I have a function to login with facebook using react-native-fbsdk:

handleFacebookLogin () {
LoginManager.logInWithReadPermissions(['public_profile']).then(
  function(result) {
    if (result.isCancelled) {
      alert('Login isCancelled');
    } else {
      alert('Login ok')
      this.props.navigation.navigate('ListaUf')
    }
  },
  function(error) {
    alert('Error: ' + error);
  }
);
}

When the user is successfully logged in, I want to navigate to the next page, which is called ListaUf.

if I use the this.props.navigation.navigate('ListaUf') in a button or in a componentDidMount, this works correctly.

On the emulator, appears a yellow message:

TypeError: undefined is not a function (evaluating 'this.props.navigation')

The alert('Login ok') works, but this.props.navigation.navigate('ListaUf') does not work.


Solution

  • You are losing context of this. You need to either bind your functions or use arrow functions. If handleFacebookLogin is being triggered with a button press or similar you need to bind it too.

    With bind

    handleFacebookLogin () {
      LoginManager.logInWithReadPermissions(['public_profile']).then(
        function(result) {
          if (result.isCancelled) {
            alert('Login isCancelled');
          } else {
            alert('Login ok')
            this.props.navigation.navigate('ListaUf')
          }
        }.bind(this),
        function(error) {
          alert('Error: ' + error);
        }
      );
    }
    

    With lambda

    handleFacebookLogin = () => {
      LoginManager.logInWithReadPermissions(['public_profile']).then(
        (result) => {
          if (result.isCancelled) {
            alert('Login isCancelled');
          } else {
            alert('Login ok')
            this.props.navigation.navigate('ListaUf')
          }
        },
        function(error) {
          alert('Error: ' + error);
        }
      );
    }