I'm new to react so I'm sure I'm missing something basic. I'm getting undefined for this, and therefore cannot read property 'setState' attempting to set state within the return of a function that calls fetch, what am I doing wrong? Note I call MyAction from an onClick and the response data is fine.
var ItemComponent = React.createClass({
getInitialState: function() {
return {
the_message: "call that API!"
};
},
doFetch: function() {
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
return fetch('http://localhost:1337/site/test', obj)
.then(function(response) {
return response.json();
}).then(function(data) {
return data;
}).catch((error) => {
console.error(error);
});
},
MyAction: function() {
this.doFetch().then(function(response){
this.setState({
the_message: response.message
});
})
},
render: function() {
return (
<div>
<div>{this.props.title}</div><br></br>
<div>{this.props.price}</div><br></br>
<div onClick={this.MyAction}>{this.props.qty}</div>
</div>
);
}
});