Problem picking up user information with React-Native-fbsdk

Asked

Viewed 273 times

0

I have a mobile app made in React On, I am logging in via facebook using lib React-Native-fbsdk but it works but I am having problems in redeeming user data, I had to see some topics here on the forum of the same situation and followed as some of them but still does not work. I’m gonna knock down the code I’m using.

Login function

loginFacebook = () => {
  LoginManager.logInWithPermissions(["public_profile", "email"]).then(
    function(result) {
      if (result.isCancelled) {
        console.log("Login cancelled");
      } else {
        AccessToken.getCurrentAccessToken().then(data => {
          const processRequest = new GraphRequest(
            "/me?fields=name,email,picture.type(large)",
            null,
            this.get_Response_Info
          );
          new GraphRequestManager().addRequest(processRequest).start();
        });
      }
    },
    function(error) {
      console.log("Login fail with error: " + error);
    }
  );
};

Function that should take the data

get_Response_Info = (error, result) => {
  if (error) {
    Alert.alert("Error fetching data: " + error.toString());
  } else {
    console.log(result.toString());
  }
};

In this function the console.log(result) does not execute I think because in the console not well anything.

1 answer

0


I used React-Native-fbsdk some time ago, and I did it as follows, I created a separate file with all the login logic.

import {
  LoginManager, AccessToken, GraphRequest, GraphRequestManager,
} from 'react-native-fbsdk';

import { AsyncStorage } from 'react-native';

const getAccountInfo = accessData => new Promise((resolve, reject) => {
  new GraphRequestManager()
    .addRequest(
      new GraphRequest(
        '/me',
        {
          accessToken: accessData.accessToken,
          parameters: {
            fields: {
              string: 'id, name, email, picture.type(large)',
            },
          },
        },
        (error, result) => {
          if (error) {
            return reject(error);
          }

          return resolve(result);
        },
      ),
    )
    .start();
});

export const facebookLogin = async () => {
  let result;
  let accessData;
  try {
    const offlineUser = await AsyncStorage.getItem('@Facebook:accessData');

    if (offlineUser) {
      accessData = JSON.parse(await AsyncStorage.getItem('@Facebook:accessData'));
    } else {
      result = await LoginManager.logInWithPermissions(['public_profile', 'email']);

      if (result.isCancelled) {
        return { error: 'Usuário cancelou o Login!' };
      }
      accessData = await AccessToken.getCurrentAccessToken();
      await AsyncStorage.setItem('@Facebook:accessData', JSON.stringify(accessData));
    }
    const info = await getAccountInfo(accessData);
    return { user: info };
  } catch (err) {
    await AsyncStorage.removeItem('@Facebook:accessData');
    // return err.userInfo[Object.keys(err.userInfo)[2]].body;
    return { error: 'Houve um erro ao recuperar os dados!' };
  }
};

On the screen where I have the Facebook login button, I imported this file and created a function to link to the button:

import { facebookLogin } from "../../services/facebook";

login_facebook = async () => {
    this.setState({ loading_facebook: true, loading: false });
    const response = await facebookLogin();
    if (response.error) {
      //Se o tipo do erro foi token expirado, chamar de novo a rotina para gerar um token novo

      this.setState({ error: response.error, loading: false });
      return false;
    }

    this.setState({
      user: response.user,
      loading: false,
      error: "",
      social_id: response.user.id,
      email: response.user.email,
      username: response.user.name,
      social_origem: "FACEBOOK"
    });
    this.autenticar_social();
  };

I took this project as a basis

https://github.com/Rocketseat/academy-facebook-auth

Here is a tutorial explaining the installation:

https://medium.com/reactbrasil/instalando-o-react-native-fbsdk-do-jeito-certo-9f0fada5be4

  • Thanks for the help, thanks to that I’ll get it the right way and get it to work as I wanted and that’s exactly what you indicated, thank you

  • Just to supplement the question for those who come to help, I have now followed and implemented according to your orders and yes this perfect to work as wanted, thanks again

Browser other questions tagged

You are not signed in. Login or sign up in order to post.