0

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 });
        }
    });
}
royhowie
  • 11,075
  • 14
  • 50
  • 67
Mariano Córdoba
  • 1,097
  • 1
  • 13
  • 29
  • Your working version is the normal way this is solved. See http://stackoverflow.com/questions/24539521/javascript-owner-of-this/24539572#24539572 – Barmar Sep 25 '15 at 00:45

1 Answers1

1

You have two other options:

Function.prototype.bind:

success: function (result) {
    // etc
}.bind(this)

An arrow function (requires es6), which uses the this from the surrounding scope:

success: (result) => {
    // etc
}
royhowie
  • 11,075
  • 14
  • 50
  • 67