Creating a Bar Chart with React and D3

I’ve been working on the Bar Chart Project in the Data Viz exercises. The component where I call the data is below, but I don’t get any response at all. Am I doing something wrong?

class DataStuff extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      gdpData: [],
    };
  }
  
  componentDidMount() {
    d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function (data) {
    var dataSet = data.data;
    console.log(dataSet);
});
  }
  
  render() {

    return (<p>Data: {}</p>)
  };
}

ReactDOM.render(<DataStuff />, document.getElementById('root'));

Hi!

You don’t see the code on the console either? Because if You expect to see it under the <p></p> You’re missing the data inside the {}:

componentDidMount() {
    d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function (data) {
        var dataSet = data.data;
        console.log(dataSet);
        this.setState({
            theData: data.data
        });
    });
}

render() {
  return (<p>Data: {this.state.theData}</p>);
}

Correct - I’m not seeing it on the console. When I check the devtools network tab, it shows I’m getting a response, but I can’t seem to print it to the console!

I’ve found the problem. The d3.json uses the Fetch API, hence it must be used like this:

d3.json('url_to_resource').then((response) => console.debug(response.data))

Example: https://codesandbox.io/s/d3json-from-react-1p69i

From the d3 docs:

Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.

The Fetch part is the important part :slight_smile: (to take into account in the future).

1 Like

That worked! How were you able to determine it uses the Fetch API? So I know what to look for in the future?

By reading the documentation :stuck_out_tongue: (the docs are Your best friend, always. Otherwise You have to read and understand the code–I’ve had to read code to understand what I needed to finish a project). The quoted text (in my previous comment) is from the docs, and whenever You see something like promise or fetch (or fetch API), then You’re dealing with asynchronous content, which is handled with a different syntax.

Read about Promises and the Fetch API.

:slight_smile:

1 Like