1

I'm attempting to load a JSON feed into my React component using componentDidMount. When I initially pull the JSON feed everything checks out, I can see the JSON data just fine. The problem exists when I try to dive deeper into the JSON data to get game information that I start getting undefined errors.

Here is my React JS:

var MLBScores = React.createClass({
  getInitialState: function() {
    return {
      hometeam: '',
      awayteam: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.feed, function(result) {

    var scoreFeed = result;

    var homeTeamName = scoreFeed.games.game[0].home_team_name;


      console.log(homeTeamName);

    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return ( < div > {
        this.state.hometeam
      }
      vs. {
        this.state.awayteam
      } < /div>
    );
  }
});

ReactDOM.render( < MLBScores feed= "https://raw.githubusercontent.com/erwstout/pinetar/develop/src/client/app/mlb-scoreboard.json" / > ,
  document.getElementById('container')
);

It's worth noting that if I just comment out the var homeTeamName line and change the console.log(homeTeamName) to console.log(result); it prints the JSON data.

I've fleshed out some of the data (and my ideas) before moving into React, with this codepen so I'm a pretty familiar with the structure of the json file. So I'm wondering if it has something to do with how I'm making the call in React? This is my first time using React so it could be me missing something. In my codepen I'm getting the data for each game but for the purpose of testing it in React I was just trying to get game[0] information.

I have a JS Fiddle of the React code as well. Any help would be appreciated. I was following along with the React Documentation a bit to get to this point but I'm lost. Thanks!

2 Answers 2

2

The return is a string, not object. Modify this to get your home team name var scoreFeed = JSON.parse(result).data;

or you use getJSON()

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

Comments

1

I didn't dive too deep into your JSON response but a ternary might help..

var homeTeamName = 
scoreFeed.games && scoreFeed.games.game[0]scoreFeed ? scoreFeed.games.game[0].home_team_name : 
null

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.