How do I create a Facebook Login with Expo React Native and Firebase

Viewed 1049

I'm quite new to React Native and Expo and would much appreciate it if I could get some help on how to create a Facebook Login. For now I have done this, but I don't know how to hook the token I get from Facebook to my app so that I have the credentials and allow login.

  try {
    await Facebook.initializeAsync({
      appId: 'myId',
    });
    const { type, token, expirationDate, permissions, declinedPermissions } =
      await Facebook.logInWithReadPermissionsAsync({
        permissions: ['public_profile'],
      });
    if (type === 'success') {

      const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
    } else {
      type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`).finally();
  }
}
2 Answers

If you're trying to use the token strictly to allow login then save it to state so it can be accessed anywhere in the app.

export const fbState = {
   fbTkn = <token>,
   isUserLoggedIn = false 
}

If you want to save the token to state then either use a Hook (useState) or install React Redux, create a store, set up an action with the snippet from expo that you posted above, then send the token you receive to the reducer.

Then you can do a boolean check to see if the user is logged in and allow them access to your app as well as have access to the token to use FB's API.

Generally, the token is used to access the Facebook API in order to request/send information such as the user's name or email address within an app. Below is an example from their JS SDK where we request the user's email, birthday, first name and last name

FB.api(
      '/me',
      'GET',
      {"fields":"id, email, birthday, first_name, last_name"},
      function(response) {
         // DO SOMETHING WITH response.json() 
      }
   );

returns response.json(): 
        {
  "id": "<user_fbid>",
  "email": "<user_email>",
  "birthday": "<user_birthday>",
  "first_name": "<user_first_name>",
  "last_name": "<user_last_name>"
}

Expo does a pretty good job of documenting Facebook integration here --> https://docs.expo.dev/versions/latest/sdk/facebook/#installation

Here is FB's 'Getting Started' walk through (they even have a sandbox to test the api) --> https://developers.facebook.com/docs/graph-api/get-started

PLEASE NOTE Expo's Facebook SDK is depreciating and they suggest using this community sourced project - https://github.com/thebergamo/react-native-fbsdk-next/#expo-installation

Related