Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

React this.setState is not a function

I'm new in React and I'm attempting to write an application working with an API. I continue to get this mistake:

at the point when I attempt to deal with the API response. I speculate it's some kind of problem with this limiting yet I can't sort out some way to fix it. Here's the code of my component:

var AppMain = React.createClass({
getInitialState: function() {
return{
FirstName: " "
};
},
componentDidMount:function(){
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}

});
}, function(){
console.info("API initialisation failed");

}, '5.34');
},
render:function(){
return (
<div className="appMain">
<Header />
</div>
);
}
});
by

2 Answers

rahul07
You can avoid the need for .bind(this) with an ES6 arrow function.

VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}

});
kshitijrana14
React recommends bind this in all methods that needs to use this of class instead this of self function.
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}

onClick () {
this.setState({...})
}

Or you may to use arrow function instead.

Login / Signup to Answer the Question.