M
M
Misha Kogan2015-09-10 10:14:27
JavaScript
Misha Kogan, 2015-09-10 10:14:27

How not to get undefined in react.js?

Hello, the essence of the problem is that I load json from the server via ajax, and parse it through react for rendering, and at the first start I always get undefined, and then I get the data as it should be. How to fix the problem?
The code:

var Game = React.createClass({
  getInitialState: function() {
    	return {data: []};
 	},
 	loadCommentsFromServer: function() {
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        cache: false,
        success: function(data) {
        	console.log(data[0]._id);
          this.setState({data: data[0]});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
  	},
  componentDidMount: function() {
      this.loadCommentsFromServer();
      setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="gameBox">
      <h1> Game id: {this.props._id}</h1>
      <Bet data={this.state.data} />
      </div>
    );
  }
});

//Comment list = bet
var Bet = React.createClass({
  render: function() {
                  // при первом выводе через консоль тут получаю undefined, после уже получаю объект 
    console.log(this.props.data.bets)
    var items = this.props.data.bets.map(function(item) {
      return (
        <Item name={item.name}/>
      );
    });
    return (
      <div className="bet">
        {items}
      </div>
    );

  }
});
//Comment = item
var Item = React.createClass({
  render: function() {
    return (
      <div className="item">
        <p> id: {this.props.id} </p> <br/>
        <p> lowestPrice: {this.props.lowestPrice} </p> <br/>
        <p> type: {this.props.type}</p> <br/>
        <p> icon_url: {this.props.icon_url} </p> <br/>
        <p> name: {this.props.name} </p> <br/>
        <hr/>
      </div>
    );
  }
});


React.render(
  <Game url="game"  pollInterval={2000} />,
  document.getElementById('main')
);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Pavlov, 2015-09-10
@dmitry_pavlov

And what is output to the console when console.log(this.props.data) for the first and subsequent times?

V
Vladimir Gamula, 2015-09-18
@vgtrue

That's right, the first time your component Gameis loaded without data, because the initial state datais an empty array, and you are trying to take a property betsin the component Bet.
After the first render, the event fires componentDidMountand the data is loaded -> the state changes.
If I understood everything correctly, you should change the property datain the method getInitialStateto be an object and not an array and add a check when passing data to the component Bet:

{this.state.data.bets && <Bet data={this.state.data} />}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question