Reactjs asynchronous component rendering

I want to make my component after executing my ajax request.

Below you can see my code

var CategoriesSetup = React.createClass({ render: function(){ var rows = []; $.get('http://foobar.io/api/v1/listings/categories/').done(function (data) { $.each(data, function(index, element){ rows.push(<OptionRow obj={element} />); }); return (<Input type='select'>{rows}</Input>) }) } }); 

But I get the error below because I am returning the visualization inside the made ajax request method.

Uncaught Error: Invariant Violation: CategoriesSetup.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

Is there any way to wait for my ajax request to complete before rendering starts?

+46
javascript ajax asynchronous reactjs jquery-deferred
Nov 28 '14 at 16:20
source share
1 answer

There are two ways to deal with this, and what you choose depends on which component should own the data and download status.

  • Move the Ajax request to the parent element and conditionally draw the component:

     var Parent = React.createClass({ getInitialState: function() { return { data: null }; }, componentDidMount: function() { $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) { this.setState({data: data}); }.bind(this)); }, render: function() { if (this.state.data) { return <CategoriesSetup data={this.state.data} />; } return <div>Loading...</div>; } }); 
  • Save the Ajax request in the component and visualize something else conditionally at boot time:

     var CategoriesSetup = React.createClass({ getInitialState: function() { return { data: null }; }, componentDidMount: function() { $.get('http://foobar.io/api/v1/listings/categories/').done(function(data) { this.setState({data: data}); }.bind(this)); }, render: function() { if (this.state.data) { return <Input type="select">{this.state.data.map(this.renderRow)}</Input>; } return <div>Loading...</div>; }, renderRow: function(row) { return <OptionRow obj={row} />; } }); 
+83
Nov 28 '14 at 16:28
source share



All Articles