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>
    );
  }
});
3
  • 1
    this.state.data.items is an object, not an array ! Commented Dec 25, 2015 at 3:14
  • This post explains you how to get the first value of an object stackoverflow.com/a/19138293/4774263 Commented Dec 25, 2015 at 3:20
  • try putting this.loadStuffFromServer() in componentWillMount(). You only have data in your initial state, not data.items Commented Dec 25, 2015 at 3:57

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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] });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.