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>
);
}
});
The "cannot read property 'setState' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
Syntax: We can use setState() to change the state of the component directly as well as through an arrow function. Example 1: Updating single attribute. We set up our initial state value inside constructor function and create another function updateState() for updating the state.
In constructor , we should avoid using setState() because this is the only place we directly assign the initial state to this. state . Also, we cannot directly put it in render() either since changing state each time triggers re-rendering which calls setState() again. This will result in an infinite loop.
useState returns the current state and a function to update it. But this function updates the value in an asynchronous way. That means by calling that function, the variable is not going to change immediately.
Use arrow function (() => {}
) which keeps the last scope (this
) as it is .
MyAction: function(){
this.doFetch().then((response) => {
this.setState({
the_message: response.message
});
});
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With