Harshit C.
Harshit C.

Reputation: 71

Making ajax call in Reactjs, value coming empty while rendering

I am new to React.js and trying to render the result from an ajax call using react but the data is not coming to the render() function. If you know any other best way to solve this issue or make an ajax call in react then please let mention the link for the same. Need to render data in react from an API.Below is the javascript for the same. The value is coming in componentDidMount method and result is having the value. But when I try to access in the render, then its empty. I tried to assign value to a global object array but that is also not working. Any solutions for this.The link mentioned in the post for fetching data is a working link. You can call that link in the browser and check for json field.

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function(result) {
      this.setState({
        username = result.description,
          lastGistUrl = result.html_url
      })
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    React.createElement("div", null, this.state.username, " 's last gist's url  is ",
      React.createElement("div", null, this.state.lastGistUrl, ""), ".")

  }
});



ReactDOM.render(React.createElement(UserGist, { source: "https://api.github.com/users/octocat/gists" }), document.getElementById('container'));

Fiddler link

Upvotes: 0

Views: 204

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Your code contains syntax errors. Replace = with :.

componentDidMount: function() {
  this.serverRequest = $.get(this.props.source, function(result) {
    this.setState({
      username: result.description,
      lastGistUrl: result.html_url
    })
  }.bind(this));
},

More errors to come:

  • render missing return statement. Should be return React.createElement
  • result is an array not an object. You need to somehow handle this. For example pick the first element result = result[0]
  • setState is method. You should call it not make an assignment setState=({}) should be setState({}) This one was in demo code.

See fixed demo.

Upvotes: 2

Related Questions