0

I am currently practising React and getting used to charts.

I had a tough time when using React chart and calling Axios to get information from online JSON file.

It works perfectly with pre-programmed values but when calling using Axios it dosn't produce a result.

I have doubts regarding how to apply Axios in the right way to the existing code! Any help is very appreciated.

 import React, { Component } from "react";
 import { Doughnut } from "react-chartjs-2";
 import axios from "axios";

 const headingStyle = {
  "text-align": "center"
  };

  const data = {
  labels: ["In", "out", "Balance"],
 datasets: [
 {
 //   data: [300, 100, 200],
  backgroundColor: ["#27DD73", "#FF2400", "#36A2EB"],
  hoverBackgroundColor: ["#27DD73", "#FF2400", "#36A2EB"]
  }
    ]
  };



 class DoughnutExample extends Component {
 async componentDidMount() {
    const { data: users } = await axios.get(
      "https://api.myjson.com/bins/bw0u4"
    );
    this.setState({ users });
  }
 render() {
 return (
  <div className="card card-1" style={{ padding: "10px" }}>
    <h3 style={headingStyle}>Cash Flow</h3>
    <Doughnut data={data} />
  </div>
 );
   }
 }

export default DoughnutExample;

My JSON file is here: https://api.myjson.com/bins/bw0u4

I am looking to take the "chart" data from the JSON.

Ryan Walls
  • 191
  • 1
  • 13
Pranoy Mathew
  • 41
  • 1
  • 7

1 Answers1

1

There's no data variable in render. Since the response is stored to the state, it should be used accordingly:

<Doughnut data={this.state.users} />

If the intention is to get chart key from array elements, an array should be remapped:

this.setState({ users: users.map(({ chart }) => chart) });

Besides that, there are no problems with this snippet.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Hey Estus, thanks for helping out. I did try the "this.state.users" but getting an error called "Cannot read property 'users' of null". Any input to what might have went wrong? – Pranoy Mathew Feb 06 '19 at 07:48
  • Unless you assigned `this.state` with null, the error likely refers to another piece of code, e.g. JSON response if it differs from what you showed. – Estus Flask Feb 06 '19 at 07:55
  • I used the exact code snippet as shown above. So state is not assigned with null. Same json too. I did check the code snippet, that you gave the link to in stackblitz. It gets the data from the json, but i was trying to just show the "chart" value from json as a Doughnut chart from "react cahrt js". – Pranoy Mathew Feb 06 '19 at 08:08
  • You don't have initial state set in original code, `state = {}`. It will be null. I guess that's the problem. – Estus Flask Feb 06 '19 at 08:16
  • Estus! Thank you for the help. – Pranoy Mathew Feb 06 '19 at 08:43