title: ES6/React "this" keyword with ajax to get data from server (tutorial)
body: <p>I'm following the <a href="https://facebook.github.io/react/docs/tutorial.html" rel="nofollow">React Beginner Tutorial</a> and I'm trying to translate it into ES6.  However when I changed the <code>CommentBox</code> to an ES6 class it started giving me a <code>this.props.url</code> is <code>undefined</code> error (in the AJAX call in <code>loadCommentsFromServer</code>).  I think this has something to do with how ES6 binds <code>this</code>, but this I'm not very familiar with the language (nor React) so I'm not sure.  I've looked at the <a href="https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html" rel="nofollow">React 0.13 release notes</a> and saw this:</p>
  
  <blockquote>
    <p>React.createClass has a built-in magic feature that bound all methods to <code>this</code> automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.</p>
  </blockquote>
  
  <p>I'm not exactly sure but I thought that it meant I had to save the value of this (as in <code>let that = this</code> and <code>.bind(that)</code>) but that also gave the same <code>this.props.url</code> is <code>undefined</code> - I'm not sure where to go next.</p>
  
  <p>Here's my current code:</p>
  
  <pre><code>class CommentBox extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: []
      };
    }
    loadCommentsFromServer() {
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        cache: false,
        success: function(data) {
          this.setState({
            data: data
          })
        }.bind(this)
      });
    }
    handleCommentSubmit(comment) {
      var comments = this.state.data;
      var newComments = comments.concat([comment]);
      this.setState({ data: newComments });
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: comment,
        success: function(data) {
          this.setState({ data: data });
        },
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    }
    componentDidMount() {
      this.loadCommentsFromServer();
      setInterval(this.loadCommentsFromServer, this.props.pollInterval);
    }
    render() {
      return (
        &lt;div className="commentBox"&gt;
          &lt;h1&gt;Comments&lt;/h1&gt;
          &lt;CommentList data={this.state.data}/&gt;
          &lt;CommentForm onCommentSubmit={this.handleCommentSubmit}/&gt;
        &lt;/div&gt;
      );
    }
  };
  </code></pre>