buschschwick buschschwick - 6 months ago 211
Javascript Question

.map is not a function React

I'm working on a small app that will pull some data from a JSON file (game scores). Currently I am getting the error,

games.map is not a function
. I saw another post on Stack Overflow that was similar, but the answer was that the initial state was not an array, but I have set my initial state to be an array, so I don't believe it applies. Below is my React JS can anyone point me in the right direction? Could it have something to do with the JSON structure? You can find the json file here. Thank you kindly!

class SingleGame extends React.Component{
render(){
return(
<div>{this.props.homeTeam}</div>
);
}
}

class GameBox extends React.Component{

constructor() {
super();

this.state = {
games: []
};
}

componentWillMount() {
this._getGameScores();
}

componentDidMount() {
this._timer = setInterval(() => this._getGameScores(), 45000);
}

componentWillUnmount() {
clearInterval(this._timer);
}

_getGameScores(){
jQuery.ajax({
method: 'GET',
url: 'http://pinetar-app.com/src/client/app/mlb-scoreboard.json',
success: function(games){
this.setState({games: games.data});
}.bind(this)
});
}

_mapGameScores(){
const games = this.state.games;

return games.map((games) => {
return(
<SingleGame homeTeam={games.game.home_team_name} />
);
});
}

render() {
const gameList = this._mapGameScores();
return(
<div>
{gameList}
</div>
);
}
}

ReactDOM.render(
<GameBox />, document.getElementById('pinetar')
);

Answer

You aren't accessing the array properly, try using mapping over this:

data.data.games.game 

like so:

Working example

_getGameScores(){
    jQuery.ajax({
      method: 'GET',
      url: 'http://pinetar-app.com/src/client/app/mlb-scoreboard.json',
      success: function(data){
        this.setState({games: data.data.games.game });
      }.bind(this)
    });
  }
Comments