[Chartjs]-Create Chart using Reactjs Chartjs and axios

0👍

You need to make two adjustments in your code.

1. Load data in componentDidMount

Change this line

componentWillMount = () => this.getChartData();

to

componentDidMount() {
  this.getChartData();
}

You need to load the data once the component is mounted on the DOM.

2. Render only when you have chart data

Conditionally render Chart component.

render() {
  return (
    <div className="App">
      {Object.keys(this.state.chartData).length &&
        <Chart
          chartData={this.state.chartData}
          location="Massachusetts"
          legendPosition="bottom"
        />
       }
    </div>
  );
}

You should render your Chart only after chartData is populated from API response.

0👍

it’s work
my mistakes in json enter code here

 getChartData() {
    axios.get("http://www.json-generator.com/api/json/get/cghIWRNGEO?indent=2").then(res => {
        const coin = res.data;
        let labels = coin.chartData.labels;
        let data = coin.chartData.datasets.data;
        // console.log(data.Object.values(data)[0])
        // data.forEach(element => {
        // data.push(element.data);
        //   });

        this.setState({
          chartData: {
            labels:labels,
            datasets: [
              {
                label: "Population",
                data: data,
                backgroundColor: [
                  "rgba(255, 99, 132, 0.6)",
                  "rgba(54, 162, 235, 0.6)",
                  "rgba(255, 99, 132, 0.6)"
                ],
              }
            ]
          }
        });
      });
    }

Leave a comment