score:4

Accepted answer

after working out the problem, it turned out that there was no problem with fetch. it just didn't account for null in any of the components in the program (it would crash after using a null value.

for example in render:

render() {
    if (this.state.data) {
      return (
        <div>
          <sandkeygraph
            height={300}
            width={700}
            id="d3-sankey" 
            sankeydata = {this.state.data} 
          />
        </div>
      );
    }
    else {
      return <div/>
    }
}

or, the use of a ternary operator would work as well to be more concise (answer by @eliran):

return (
  {this.state.data ?
    <div>
      <sandkeygraph
        height={300}
        width={700}
        id="d3-sankey" 
        sankeydata = {this.state.data} 
      />
    </div> : <div>no data available</div>
);

score:0

...
class app extends react.component {
constructor(props) {
super(props)

  this.state = {
    data : null
  }
}

it seems like an error on the state declaration?

score:0

1.- import your json in app component on top like this: import jsondata from './data/sankey.json'

2.- set jsondata in state jsondata in app component.

constructor(props) {
  super(props)
  this.state = {
    jsondata : {}
  }
}

componentwillmount() {
     this.setstate({ jsondata })
  }

you do not need to fetch as you have your json locally.

once you have your json in your state, you can display it in render like this for example:

this.state.jsondata.data.links.map(x=>
  <div>
   <div>x.links.source</div>
   <div>x.links.target</div>
  </div>
)

score:0

i've been testing and you need to replace the getdata() method to this:

  getdata = (uri) => {
    fetch(uri, {
      headers : { 
        'content-type': 'application/json',
        'accept': 'application/json'
       }
    })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      // successful got the data
      console.log(data);
      this.setstate({ data });
   });
  }

this is because you need to declare 'content-type' and 'accept' headers on your fetch options in order to make your request.

score:1

you can add in your render function a condition:

render() {
// failed
const { data } = this.state;
return (
  <div>
    {data ?
    <sandkeygraph
      height={300}
      width={700}
      id="d3-sankey" 
      sankeydata={data} 
    /> : "loading..."
    }
  </div>
);
}

and only if data is populated the component will be rendered.


Related Query

More Query from same tag