I m trying to get information through the facebook sdk but so far I am getting only the id and the name of the user. I do have granted the premission but still the email is not popping out like name and id.
I try to console.log(result.email) but i got undefined .
Any help would be appreciated.
Thanks in advance
import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken ,GraphRequest, GraphRequestManager} from 'react-native-fbsdk';
export default class Login extends Component {
render() {
return (
<View>
<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)
console.log(result.email)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
}
Related
I am fetching a big problem with axios in my project. I used axios for fetching data in getServerSideProps. but is it showing 'Request failed with status code 404', in the same time i also used axios in useEffect where it get data from api.
export async function getServerSideProps() {
try {
const ApiUrl = apiBaseUrl + "/api/my-url";
const homeData = await axios
.get(ApiUrl)
.then((response) => {
return response.data;
})
.catch((error) => {
return error.message;
});
return {
props: {
homeData: homeData, // its is return Request failed with status code 404
error: false,
ApiUrl: ApiUrl,
},
};
} catch (e) {
return {
props: {
error: true,
homeData: null,
message: e.message,
},
};
}
}
through i cna not get data from getServerSideProps i used useEffect
useEffect(() => {
if (typeof props.homeData === "string") {
console.log(props); // it is showing error 'Request failed with status code 404'
} else if (props.homeData) {
console.log(props.homeData);
// setData(props.homeData);
} else {
axios
.get(apiBaseUrl + "/api/my-url")
.then((response) => {
seteData(response.data);
})
.catch((error) => {
console.log(error);
});
}
}, [props]);
I'm working in with react-native-fbsdk. I want to get username and email to show up to the user when they're registered to the app in order to create a profile for the app, but no data is shown. How can I get these data and how can I show it in a different screen.
This is my code
import FBSDK from 'react-native-fbsdk'
import { LoginButton,AccessToken,GraphRequest,GraphRequestManager} from 'react-native-fbsdk';
const {
LoginManager,
} = FBSDK;
<LoginButton
readPermissions={['public_profile']}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
const infoRequest = new GraphRequest(
'/me?fields=name,picture',
null,
this._responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
_responseInfoCallback = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
alert('Result Name: ' + result.name);
}
}
}
Thanks friends
I retrieve facebook login while I using firebase.
import this file:
import firebase from "react-native-firebase";
import { AccessToken, LoginManager } from "react-native-fbsdk";
Firebase login code work when I click button:
export const fbLogin = () => {
LoginManager.logInWithReadPermissions(["public_profile", "email"])
.then(result => {
if (result.isCancelled) {
console.log("Login was cancelled");
}
return AccessToken.getCurrentAccessToken();
})
.then(data => {
const credential = firebase.auth.FacebookAuthProvider.credential(
data.accessToken
);
firebase
.auth()
.signInWithCredential(credential)
.then(result => {
Toast.show({
text: "Sucessfully",
position: "top"
});
console.log("Successfully Login", result);
})
.catch(error => {
console.log("Failed", error);
});
})
.catch(err => {
console.log("fail", err);
});
};
I retrive my facebook login data
console.log("Successfully Login", result);
result contains username, email, picture and ..ect credentials
If you don't want to use firebase,
const infoRequest = new GraphRequest(
'/me?fields=name,email,picture.type(large)',
null,
this._responseInfoCallback
);
new GraphRequestManager().addRequest(infoRequest).start();
_responseInfoCallback = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
this.setState({ userName: result.name, userEmail: result.email ,userPic:result.picture.data.url});
AsyncStorage.setItem("UserName",this.state.userName);
AsyncStorage.setItem("Email", this.state.userEmail);
AsyncStorage.setItem("UserPic", this.state.userPic);
// SharedPreferences.setItem("UserName", this.state.userName);
// SharedPreferences.setItem("Email", this.state.userEmail);
// SharedPreferences.setItem("UserPic", this.state.userPic);
console.log("Picture"+ this.state.userPic + "Name" + this.state.userName + "Email" + this.state.userEmail);
}
}
Im using navigation control in ionic provider whenever i triggered the provider it shows the runtime error Cannot read property 'pop' of null
my code is
#Injectable()
export class ServerResponseProvider {
#ViewChild('myContent') navCtrl: NavController;
constructor(public http: Http, public alertCtrl: AlertController,
protected injector: Injector, private app:App) {
console.log('Hello ServerResponseProvider Provider');
}
httpGetRes(url) {
return Observable.create(observer => {
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
console.log("response:", data);
observer.next(data);
}, (err) => {
console.log("Your error : ", err);
observer.error(err);
if (err.status == 400) {
this.alertC('Validation Error');
} else if (err.status == 403) {
this.alertC('Authorization error')
} else if (err.status == 500) {
this.alertC('Something went wrong try again later')
}
});
});
}
alertC(msg) {
let alert = this.alertCtrl.create({
title: ' OOPS !!!!',
subTitle: msg,
buttons: [{
text: 'ok',
handler: () => {
this.navCtrl.pop();
}
}]
});
alert.present(alert);
}
}
i tried in many ways it wont works
thanks in advance
i'm trying to do login to my app with facebook,
i installed the cordova facebook plugin
and this my code but i get error on Promise
this is my code(actually i just copied it from tutorial that say it works for him)
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import {Http, Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
declare const facebookConnectPlugin: any;
#Component({
templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
posts:any;
constructor(public platform: Platform, private navCtrl: NavController,private http: Http)
{ this.platform = platform;
this.http = http;
}
fblogin()
{
this.platform.ready().then(() => {
this.fblogin1().then(success => {
console.log("facebook data===" + success);
alert("facebook data===" + success);
this.http.post('http://localhost/facebook.php',success)
.map( res =>res.json()).subscribe(data => {
if(data.msg=="fail")
{
console.log('Login failed');
alert("Invalid username and password");
return;
}
else
{
console.log(' login Sucessfully facebook');
}
});
}, (error) => {
alert(error);
});
});
}
fblogin1(): Promise<any>
{
return new Promise(function(resolve,reject)
{
facebookConnectPlugin.login(["email"], function(response)
{
alert(JSON.stringify(response.authResponse));
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,email,gender',[],
function onSuccess(result)
{
//alert(JSON.stringify(result));
//console.log(JSON.stringify(result));
resolve(JSON.stringify(result));
},
function onError(error)
{
alert(error);
}
);
},
function(error)
{
alert(error);
})
});
}
}
if anyone know another way i would like to know.
i solve this issue by changing the login function to this code
facebookLogin(){
Facebook.login(['email']).then( (response) => {
let facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
var that = this;
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
that.userProfile = JSON.stringify(success);
that.nav.setRoot(HomePage);// after login go to HomePage
})
.catch((error) => {
console.log("Firebase failure: " + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}
I'm trying to share an image to Facebook in React Native through the react-native-fbsdk package.
I have the following, copied almost completely from the docs, but I can't figure out how to format the imageUrl, I keep getting errors saying the SharingContent is invalid.
What am I doing wrong here?
const sharePhotoContent = {
contentType: 'photo',
photos: [
{
imageUrl: "./local/image/path.png",
userGenerated: false,
caption: "Hello World"
}
]
};
ShareDialog.canShow(sharePhotoContent).then(
function(canShow) {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
}
).then(
function(result) {
if (result.isCancelled) {
AlertIOS.alert('Share cancelled');
} else {
AlertIOS.alert('Share success with postId: ' + result.postId);
}
},
function(error) {
AlertIOS.alert('Share fail with error: ' + error);
}
);
You can use the react-native-image-picker https://github.com/marcshilling/react-native-image-picker to get the uri of the image and use it create a SharePhotoContent.
Also note that you need to have the facebook app installed in order to share an image.
This is working fine for me
shareLinkWithShareDialog() {
let shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.facebook.com/images/fb_icon_325x325.png',
contentDescription: 'Facebook sharing is easy!'
}
ShareDialog.canShow(shareLinkContent).then((canShow) => {
if (canShow) return ShareDialog.show(shareLinkContent);
}
).then((result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
function(error) {
alert('Share fail with error: ' + error);
}
);
}