Ad

Return Array Iteration

- 1 answer

I've got the following component where I pull in some JSON and I'm trying to get some nested information with { this.state.data.items[0]}, however I get the error:Uncaught TypeError: Cannot read property '0' of undefined, although {this.state.data} and {this.state.data.items} works as well

Here's the full code:

var Box = React.createClass({
      getInitialState: function () {
    return {data: []};
  },
  loadStuffFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function() {
    this.loadStuffFromServer();
    setInterval(this.loadStuffFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div>
        { this.state.data.items[0]}
      </div>
    );
  }
});
Ad

Answer

Your getInitialState should looks like this

getInitialState: function () {
    return { 
       data: {
          items: []
       } 
    };
},

because render calls before componentDidMount., you are trying get property items from state.data but this property does not exists

this.state.data       // => returns empty Array

then you are trying get property items

this.state.data.items // => returns undefined

because data does not have property items.,

then you are trying get first element from itemsArray but previous statement returned undefined, and that's why you get Error, because you can not get properties from undefined value

Ad
source: stackoverflow.com
Ad