Im trying to make a simple comment system using React. I'm saving the comments in Parse. The problem is, when I retrieve the comments from Parse, I need to update the state of my component, but when I try to do it, I get an error "Uncaught ReferenceError: this.setState is not defined"
.
Not working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
this.setState({ data: data });
}
});
}
If I change my code it works, but I think that should have a better approach to this.
Working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
let _this = this;
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
_this.setState({ data: data });
}
});
}