react - json from url

- 1 answer

Ad

I'm going through the react tutorial here -

http://facebook.github.io/react/docs/tutorial.html

And I'm having problems on step 11 "Fetching from the Server"

Here is my .js file -

var WGGroupList = React.createClass({
  render: function() {
    var wggroupNodes = this.state.data.map(function(wggroup) {
      return (
        <WGGroup name={wggroup.name} key={wggroup.id}>
          {wggroup.description}
        </WGGroup>
      );
    });
    return (
      <div className="wggroupList">
        {wggroupNodes}
      </div>
    );
  }
});

var WGGroupForm = React.createClass({
  render: function() {
    return (
      <div className="wggroupForm">
        Hello, world! I am a Widget Group Form.
      </div>
    );
  }
});

var WGGroupBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  render: function() {
    return (
      <div className="wggroupBox">
        <h1>Description</h1>
        <WGGroupList data={this.state.data} />
//        <WGGroupList data={this.props.data} />
        <WGGroupForm />
      </div>
    );
  }
});

var WGGroup = React.createClass({
  render: function() {
    return (
      <div className="wggroups">
        <h2 className="wggroupName">
          {this.state.data.name}
        </h2>
        {this.state.data.children}
      </div>
    );
  }
});

ReactDOM.render(
  <WGGroupBox data="http://servername/api/wggroups/?format=json" />,
//  <WGGroupBox data={data} />,
  document.getElementById('content')
);

It works if I do the example previous with the data hardcoded -

var data = [
  {id: 1, name: "Primary Widgets", description: "This is my Primary Widget group"},
  {id: 2, name: "Secondary Widgets", description: "This is my secondary Widget group"}
];

The json served from the API is exactly the same format as above. So why, if using my URL do I get the following -

Uncaught TypeError: Cannot read property 'data' of null

It's failing on this line -

var wggroupNodes = this.state.data.map(function(wggroup) {

If I debug in my browser the datasource is not showing up so I'm guessing the issue is why is it not loading the url data?

Ad

Answer

Ad

I checked step 11 in the Tutorial and came across this sentence:

"Note: the code will not be working at this step."

At step 13 the function that fetches data from a server is introduced.. right now you are just passing a url-string around.

Ad
source: stackoverflow.com
Ad