Ad

Why Is 'this.setState' Not Working?

- 1 answer

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?

Ad

Answer

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

Ad
source: stackoverflow.com
Ad