Search code examples
javascriptreactjsaxiosreact-chartjs

Add Axios to React chart and take JSON data


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.


Solution

  • 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.