Issue
I'm integrating Facebook login into a React Native app that I'm building. I have the following code:
class FacebookButton extends Component {
constructor(props) {
super(props);
this.fetchAccessToken = this.fetchAccessToken.bind(this);
}
facebookButtonPressed() {
LoginManager.logInWithReadPermissions(['public_profile']).then((result) => {
if (result.isCancelled) {
console.log('Login Cancelled');
} else {
this.fetchAccessToken();
}
})
.catch((error) => {
console.log('Login fail with error: ' + error);
});
}
fetchAccessToken() {
AccessToken.getCurrentAccessToken().then((data) => {
const { accessToken } = data
console.log(accessToken);
})
.catch(() => {
console('Error getting access token');
});
}
render() {
return (
<Button
onPress={this.facebookButtonPressed}
title="Sign In with Facebook"
color="#000000"
/>
);
}
}
However, I keep getting the error that the fetchAccessToken
method is not a function. On first instinct, I thought that the issue this
keyword was the issue. So I began with adding the above construct and binding this
to it. I assumed here that this
meant FacebookButton
. i.e. I assumed that whenever I called this.fetchAccessToken()
it would call the method. However, this didn't work.
I then continued reading and there were several references stating that I should use Arrow functions
as arrow functions don't have a this
associated with this function and this this.fetchAccessToken()
would only have one context i.e. FacebookButton
. However, this still isn't working.
So I have questions:
- What are the exact issues that are causing the above code to not work? A details intuition would be appreciated. I'm taking React Native for a spin for the first time.
- What would the fix be?
Update
The answer to question 2 is to add .bind(this)
to the button like so:
<Button
onPress={this.facebookButtonPressed.bind(this)}
title="Sign In with Facebook"
color="#000000"
/>
Solution
You also need to bind facebookButtonPressed()
in the constructor to reference this
for the fetchAccessToken
as
constructor(props) {
super(props);
this.facebookButtonPressed = this.facebookButtonPressed.bind(this)
this.fetchAccessToken = this.fetchAccessToken.bind(this);
}
When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), how the function was invoked, what parameters were passed, etc.
Right now that is not referenced, unless you bind it.
Here are some of the different ways of binding
.The methods have been explained by their pros and cons
Also you can learn more about this
from here
Answered By - Pritish Vaidya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.