1

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>
    );
  }
});
the_
  • 1,183
  • 2
  • 30
  • 61

2 Answers2

1

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 items Array but previous statement returned undefined, and that's why you get Error, because you can not get properties from undefined value

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

render function can not get your data.item from initial state.you should need to change :

this.state.data.map(function(d){ return d.items[0] });
Ryan.Ruan
  • 66
  • 3