React native firebase - facebook sign-in not triggering onAuthStateChanged listener

Viewed 193

this is the second problem Im having with RNFB facebook login.

Im following the official code sample provided by RNFB....code below

Problem is with the line firebase().signInWithCredential(facebookCredential);....its not triggering the firebase listener auth().onAuthStateChanged All other code is running as it should and facebookCredential variable is populated correctly

import { firebase } from '@react-native-firebase/auth';

  onFacebookButtonPress = async () => {
    // Attempt login with permissions
    const result = await LoginManager.logInWithPermissions([
      'public_profile',
      'email',
    ]);

    if (result.isCancelled) {
      throw 'User cancelled the login process';
    }

    // Once signed in, get the users AccesToken
    const data = await AccessToken.getCurrentAccessToken();

    if (!data) {
      throw 'Something went wrong obtaining access token';
    }

    // Create a Firebase credential with the AccessToken
    //const facebookCredential = firebase.FacebookAuthProvider.credential(data.accessToken);
    const facebookCredential = firebase.auth.FacebookAuthProvider.credential(
      data.accessToken,
    );

    // Sign-in the user with the credential
    firebase().signInWithCredential(facebookCredential);
  };
2 Answers

I figured it out by putting a try/catch around the problematic line. Turned out was because I had already once signed in using Google.

An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address

You shouldn't wait till something goes wrong before you add try/ catch's. signInWithCredential returns many different types of errors, which you handle. From the docs:

firebase.auth().signInWithCredential(credential).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // The email of the user's account used.
  var email = error.email;
  // The firebase.auth.AuthCredential type that was used.
  var credential = error.credential;
  if (errorCode === 'auth/account-exists-with-different-credential') {
    alert('Email already associated with another account.');
    // Handle account linking here, if using.
  } else {
    console.error(error);
  }
 });

Please handle the other error cases too :

auth/account-exists-with-different-credential

auth/invalid-credential

auth/operation-not-allowed

auth/user-disabled

and more.

Related