TypeError: Cannot read property 'setState' of undefined
Solution 1:
Bind the callback function also so that this
inside the callback points to the context of the React Component and not the callback function
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: (data) => {
this.setState( { posts: data } )
}
});
}
or you could use bind like
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
this.setState({ posts: data })
}.bind(this)
});
}
Solution 2:
The issue is related with loosing context of this. Please try this:
let self = this;
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
self.setState( { posts: data } )
}
});
}
or you can use bind:
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
self.setState( { posts: data } )
}
});
}.bind(this)