How to use graph API with react-native-fbsdk?

后端 未结 5 1000
花落未央
花落未央 2021-01-30 17:49

I read the document, both on github and Facebook developers docs.
There is only sample, nothing more. No API document.

The code to make a Graph API request is

相关标签:
5条回答
  • 2021-01-30 18:23

    Thank you @Samuel.

    I finally succeed to get user information from Facebook login because of your help!

    But I struggled to figure out how can I get username and email literally from the result object cause I am a newbie in React & Javascript.

    P.S. result["name"] is the point because it is object!!

    So I added some code to yours for other people like me.

    If you don't like using your code, just tell me that.

    <LoginButton
      onLoginFinished={
        (error, result) => {
          if (error) {
            alert("login has error: " + result.error);
          } else if (result.isCancelled) {
            alert("login is cancelled.");
          } else {
    
            AccessToken.getCurrentAccessToken().then(
              (data) => {
                let accessToken = data.accessToken
                alert(accessToken.toString())
    
                const responseInfoCallback = (error, result) => {
                  if (error) {
                    console.log(error)
                    alert('Error fetching data: ' + error.toString());
                  } else {
                    console.log(result)
    
                    // Here's my code
                    alert('Success fetching data: ' + result["name"].toString() + 
                    ", " + result["email"].toString()); 
                    /*  
                    if(your DB already got this email or something unique) {
                      // SignIn()
                    } 
                    // when your DB doesn't have this email
                    else {
                      // Do signUp() with this infomation and SignIn()
                    }
                    */
                  }
                }
    
                const infoRequest = new GraphRequest(
                  '/me',
                  {
                    accessToken: accessToken,
                    parameters: {
                      fields: {
                        string: 'email,name,first_name,middle_name,last_name'
                      }
                    }
                  },
                  responseInfoCallback
                );
    
                // Start the graph request.
                new GraphRequestManager().addRequest(infoRequest).start()
    
              }
            )
    
          }
        }
      }
      onLogoutFinished={() => alert("logout.")}/>
    
    0 讨论(0)
  • 2021-01-30 18:24

    try this

    import { GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
    
    export const GetInfoUSer = () => {
    
    return new Promise((resolve, reject) => {
    
        const infoRequest = new GraphRequest('/me', null, ((error, result) => {
            if (error) {
                reject(error)
            } else {
               resolve(result)
            }
        }))
    
        new GraphRequestManager().addRequest(infoRequest).start();
    
      })
    }
    

    and then

        onLoginConFacebook = () => {
    
        LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
    
            if (result.isCancelled) {
                console.log(':(')
            } else {
    
                AccessToken.getCurrentAccessToken().then((data) => {
    
                    let myAccessToken = data.accessToken.toString();
    
                    GetInfoUSer().then(response => {
                        console.log(response)
                    }).catch(error => {
                        console.log(error)
                    })
                }
                ).catch(error => {
                    console.log(':(')
                })
            }
        })
    }
    
    0 讨论(0)
  • 2021-01-30 18:35

    Unfortunately the react-native-fbsdk documentation is not updated and the examples do not work well.

    I got the same problem and I solved it by try and error.

    To solve your problem you'll need to change your GraphRequest adding params and fields to it like this:

      <LoginButton
        onLoginFinished={
          (error, result) => {
            if (error) {
              alert("login has error: " + result.error);
            } else if (result.isCancelled) {
              alert("login is cancelled.");
            } else {
    
              AccessToken.getCurrentAccessToken().then(
                (data) => {
                  let accessToken = data.accessToken
                  alert(accessToken.toString())
    
                  const responseInfoCallback = (error, result) => {
                    if (error) {
                      console.log(error)
                      alert('Error fetching data: ' + error.toString());
                    } else {
                      console.log(result)
                      alert('Success fetching data: ' + result.toString());
                    }
                  }
    
                  const infoRequest = new GraphRequest(
                    '/me',
                    {
                      accessToken: accessToken,
                      parameters: {
                        fields: {
                          string: 'email,name,first_name,middle_name,last_name'
                        }
                      }
                    },
                    responseInfoCallback
                  );
    
                  // Start the graph request.
                  new GraphRequestManager().addRequest(infoRequest).start()
    
                }
              )
    
            }
          }
        }
        onLogoutFinished={() => alert("logout.")}/>
    

    You'll need to enable the Remote JS Debug to see the console.log() info. https://facebook.github.io/react-native/docs/debugging.html

    And probably you need to get some permissions to get more info than names and email so it's a good idea to look the Facebook Graph API Documentation: https://developers.facebook.com/docs/graph-api/overview/

    Reference:

    https://github.com/facebook/react-native-fbsdk/issues/105#issuecomment-206501550

    0 讨论(0)
  • 2021-01-30 18:38

    Here is an example of a custom button if you want to make one :)

    FbLoginButton() {
     LoginManager
      .logInWithReadPermissions(['public_profile'])
      .then(function (result) {
        if (result.isCancelled) {
          alert('Login cancelled');
        } else {
          AccessToken
            .getCurrentAccessToken()
            .then((data) => {
              let accessToken = data.accessToken
              alert(accessToken.toString())
    
              const responseInfoCallback = (error, result) => {
                if (error) {
                  console.log(error)
                  alert('Error fetching data: ' + error.toString());
                } else {
                  console.log(result)
                  alert('Success fetching data: ' + result.toString());
                }
              }
    
              const infoRequest = new GraphRequest('/me', {
                accessToken: accessToken,
                parameters: {
                  fields: {
                    string: 'email,name,first_name,middle_name,last_name'
                  }
                }
              }, responseInfoCallback);
    
              // Start the graph request.
              new GraphRequestManager()
                .addRequest(infoRequest)
                .start()
    
            })
        }
      }, function (error) {
        alert('Login fail with error: ' + error);
       });
      }
    
    0 讨论(0)
  • 2021-01-30 18:47

    My code was not retriving the user email, if you are having the same problem, just put 'email' in parameter's logInWithPermission

    Not Working

    LoginManager.logInWithPermissions(['public_profile']).then(...)
    

    Working

    LoginManager.logInWithPermissions(['public_profile', 'email']).then(...)
    

    All Function

    loginWithFacebook = () => {
        LoginManager.logInWithPermissions(['public_profile', 'email']).then(
          login => {
            if (login.isCancelled) {
              console.log('Login Cancelado');
            } else {
              AccessToken.getCurrentAccessToken().then(
                (data) => {
                  const accessToken = data.accessToken.toString()
                  this.getInfoFromToken(accessToken)
                })
            }
          },
          error => {
            console.log('Erro no login ', console.error(error)
            )
          }
        )
      }
    
      getInfoFromToken = token => {
        const PROFILE_REQUEST_PARAMS = {
          fields: {
            string: 'id, name, first_name, last_name, birthday, email'
          },
        }
        const profileRequest = new GraphRequest('/me', { token, parameters: PROFILE_REQUEST_PARAMS },
          (error, result) => {
            if (error) {
              console.log('Login Info has an error:', error)
            } else {
              console.log(result)
            }
          },
        )
        new GraphRequestManager().addRequest(profileRequest).start()
      }
    
    0 讨论(0)
提交回复
热议问题