How to call multiple ajax at same time (and get results asychronous) in ReactJS?

I want to send multiple ajax calls in ReactJS, and I wonder if the code is executed in order. Will the second ajax call be sent only after the first ReactJS component is rendered?

var firstAJAX = React.createClass({
  componentWillMount: function() {
    this.state = {list: []};
  },
  componentDidMount: function() {
    $.ajax({
      url: '/someurl',
      dataType: 'json',
      cache: false,
      type: 'GET',
      success: function(data) {
        this.setState({list: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('url', status, err.toString());
      }.bind(this)
    })
  },
  render: function() {
    return (
        <div>
             {something}
        </div>
    )
  }
})
ReactDOM.render(<firstAJAX />,
  document.getElementById('div')
);

var secondAJAX = React.createClass({
   //similar code with different url from firstAJAX
});

I want to handle multiple document elements with the results got from ajax. How to make the send 1 ajax->render->send 1 ajax->render->... become send multiple ajaxs -> render -> render...

Answers 1

  • Assuming you add the following code after your var secondAJAX = ... declaration, the 2nd ajax call would happen after the first one rendered.

    ReactDOM.render(<secondAJAX />,
      document.getElementById('div')
    );
    

    I don't know what you're hoping to accomplish with this question, but you probably don't want to be doing things this way.


Related Articles