Reputation: 1
I am new to React Native and getting an error "this.setState is not a function". please help me to figure this out.
constructor(props) {
super(props);
this.facebookLogin = this.facebookLogin.bind(this);
this.state = {
ready: false,
email:'',
name:''
}
}
facebookLogin = () =>{
LoginManager.logInWithReadPermissions(['public_profile','email']).then(function(result){
if(result.isCancelled){
console.log('loging cancelled')
}
else {
console.log('login success' + result.grantedPermissions)
const infoRequest = new GraphRequest('/me', {
parameters: {
'fields': {
'string' : 'email,name'
}
}
},function(error, result) {
console.log(result)
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
this.setState({name: result.name, email:result.email});
}});
new GraphRequestManager().addRequest(infoRequest).start();
}
}, function(error){
console.log('An error occured: ' + error)
})
}
**this.setState({name: result.name, email:result.email}); **
<TouchableOpacity style={styles.btnfb}
onPress={this.facebookLogin}>
<Text style={styles.buttonText}>LOGIN WITH FACEBOOK</Text>
</TouchableOpacity>
Thank you.
Upvotes: 0
Views: 529
Reputation: 21
setState that you are trying to access is available in your class scope. However you are calling setstate in a function scope called by some action of yours. As a solution to your problem you need to bind this along with your function in onpress action i.e. this.facebooklogin.bind(this). So this way you have access to this of class scope in your function. You can store this in another variable in the function and use that to call setState.
Alternatively you can use ES6 arrow function to solve this issue.
Upvotes: 1
Reputation: 11577
Every time you declare a function like function () {}
it creates a new scope, so by the time you get to setState, this
is no longer your component.
A quick fix is to use arrow functions: () => {}
since it keeps the scope, or passing this
from the outer scope into where you need it thru a variable.
Upvotes: 4