2

I'm fetching JSON data from an API endpoint and want to use this data to show a table.

Here's what I'm currently trying:

var DeliveryOptionsTHeadTh = React.createClass({
  render: function() {
    return (
      <th>{this.props.label}</th>
    );
  }
});

var DeliveryOptionsTHead = React.createClass({
  getInitialState : function(){
      return {
         data : []
      }

  },

  componentDidMount: function() {
    $.get(this.props.source, function(result) {
      console.log(result);
      this.setState({data: result});
    }.bind(this));
  },

  render: function() {
    return (
      <thead>
        <tr>
          <DeliveryOptionsTHeadTh label={this.state.data.days[0].label}/>
        </tr>
      </thead>
    );
  }
});

var DeliveryOptionsTable = React.createClass({
  render: function() {
    return (
      <table className='pure-table pure-table-horizontal'>
        <DeliveryOptionsTHead source="<REDACTED>" />
        <tbody>

        </tbody>
      </table>
    );
  }
});

ReactDOM.render(
  <DeliveryOptionsTable />,
  document.getElementById('example')
)

But this returns Uncaught TypeError: Cannot read property '0' of undefined. Why is is this not working?

narzero
  • 2,199
  • 5
  • 40
  • 73

2 Answers2

2

You need change initial state., as days are Array of Objects and you are trying in render method get first element from Array but in initial state there is no days property, that's why you are getting error

var DeliveryOptionsTHead = React.createClass({
  getInitialState : function(){
    return {
      data: { days: [] } 
    }
  },

  componentDidMount: function() {
    $.get(this.props.source, function(result) {
      this.setState({data: result});
    }.bind(this));
  },

  render: function() {
    var days = this.state.data.days.map(function (day) {
      return <DeliveryOptionsTHeadTh label={day.label} key={ day.date } />;
    });

    return <thead>
      <tr>{ days }</tr>
    </thead>;
  }
});

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

It seem you have not declare your initial state, so your react is looking for the data when you called this.setState({data : result}); this should help

.....[other react specs code]

getInitialState : function(){
    return {
       data : []
    }

}
pitaside
  • 650
  • 10
  • 14
  • Tried this but does not work either. Now it returns `Uncaught TypeError: Cannot read property '0' of undefined` – narzero Jan 04 '16 at 18:22
  • `this.state.data.days[0].label should be throwing that error when trying to access an object property`. what does your result return is it a jsonObject or a jsonArray from the http call. – pitaside Jan 04 '16 at 20:15