Search code examples
javascriptjqueryajaxreactjses6-module-loader

AJAX request is not setting this.state.data in my React component.


I have recently been working with ReactJS and having an issue with setting state when using an AJAX request.

The AJAX request is making a request on the server and receiving 200 code, so I know the API request is working well. However, the React component does not seem to have this.state.data set.

Here is the component code:

export class Experiences extends React.Component {
  constructor() {
    super();
    this.state = {
      data: []
    };
  }

  loadExperiencesFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: (data) => {
        this.setState({
          data: data
        })
      },
      error: (xhr, status, err) => {
              console.error(this.props.url, status, err.toString());
      }
    });
  }

  componentDidMount() {
    this.loadExperiencesFromServer();
  }

  render () {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
          <p>{this.state.data}</p>
        </div>
    );
  }
};

And this is how I am rendering the component:

ReactDOM.render(<Experiences url='/about_me/experiences/' />, document.getElementById('genomics-geek-container'));

When I hit the API directly, I get this response:

$ http http://127.0.0.1:8000/about_me/experiences/

HTTP/1.0 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Date: Wed, 27 Apr 2016 02:15:40 GMT
Server: WSGIServer/0.2 CPython/3.5.1
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "company": "Mike",
            "created": "2016-04-27T01:30:50.425111Z",
            "degree": "test",
            "description": "test",
            "ended": "2016-04-21",
            "experience_type": 1,
            "is_current_position": true,
            "location": "test",
            "owner": "geek",
            "position": "test",
            "started": "2016-04-27"
        }
    ]
}

So I know the API is returning data and the React component is being rendered on my browser, but no data is being loaded into the component for some reason. What am I missing? Thanks in advance for the help!


Solution

  • you are losing context of this.

    in your constructor bind this to your custom function

    constructor() {
        super();
        this.state = {
          data: []
        };
        this.loadExperiencesFromServer = this.loadExperiencesFromServer.bind(this)
    }