0

I am trying to pass array of data fetched from JSON data to labels and data in charts.js as following to plot a Bar Chart:-

import React, { Component } from 'react'
import Axios from 'axios'
import Chart from './Chart'
class CaseList extends Component {
    constructor(props) {
        super(props)

        this.state = {
             posts: [] 

        }
    }

componentWillMount() {

      const {posts} = this.state
        var states=[]
        var num=[]

        for (var i=1;i<posts.length;i+=1) {
          states[i-1]=posts[i].state
          num[i-1]=posts[i].confirmed
      }

        this.getchartData(states,num);

    }

getchartData(states,num){
this.setState({
        chartData:{
          labels: states,
        datasets: [
          {
            label:'No. of Positive Cases',
            data:num,
            backgroundColor:[

              'rgba(255,3,0,1)',
              'rgba(219,3,0,1)',
              'rgba(152,3,0,1)',
              'rgba(255,3,0,0.7)',
              'rgba(101,191,217,1)',
              'rgba(101,191,217,0.59)',
              'rgba(101,79,161,0.98)',
              'rgba(208,79,197,0.98)',
              'rgba(208,79,197,0.65)',
              'rgba(43,144,197,1)',
              ]
          }
        ]
      }
      })
    }

componentDidMount() {
        Axios.get('https://api.covid19india.org/data.json')
        .then(response => {
            this.setState({posts:response.data.statewise})
            })
        .catch(error => {
            console.log(error)
        })
    }

render(){
return(
<div>
<Chart chartData={this.state.chartData} />
</div>
  )
}
}

Where Chart is another .js file as follows:-

import React, {Component} from 'react';
import {Bar} from 'react-chartjs-2';

class Chart extends Component{
  constructor(props){
    super(props);
    this.state = {
      chartData:props.chartData
    }
  }

  static defaultProps = {
    displayTitle:true,
    displayLegend: true,
    legendPosition:'right',
    location:'City'
  }

  render(){
    return (
      <div className="chart">
        <Bar
          data={this.state.chartData}
          options={{
            title:{
              display:this.props.displayTitle,
              text:'State-Wise Bar Chart',
              fontSize:25
            },
            legend:{
              display:this.props.displayLegend,
              position:this.props.legendPosition
            }
          }}
        />
        </div>
    )
  }
}

JSON Data looks something like this:-

[
        {
            "active": "23648",
            "confirmed": "33184",
            "deaths": "1081",
            "deltaconfirmed": "122",
            "deltadeaths": "2",
            "deltarecovered": "18",
            "lastupdatedtime": "30/04/2020 09:52:45",
            "recovered": "8455",
            "state": "Total",
            "statecode": "TT",
            "statenotes": ""
        },
        {
            "active": "7890",
            "confirmed": "9915",
            "deaths": "432",
            "deltaconfirmed": "0",
            "deltadeaths": "0",
            "deltarecovered": "0",
            "lastupdatedtime": "29/04/2020 22:37:46",
            "recovered": "1593",
            "state": "Maharashtra",
            "statecode": "MH",
            "statenotes": ""
        },
        {
            "active": "3358",
            "confirmed": "4082",
            "deaths": "197",
            "deltaconfirmed": "0",
            "deltadeaths": "0",
            "deltarecovered": "0",
            "lastupdatedtime": "29/04/2020 20:54:45",
            "recovered": "527",
            "state": "Gujarat",
            "statecode": "GJ",
            "statenotes": ""
        },
        {
            "active": "2291",
            "confirmed": "3439",
            "deaths": "56",
            "deltaconfirmed": "0",
            "deltadeaths": "0",
            "deltarecovered": "0",
            "lastupdatedtime": "29/04/2020 23:16:45",
            "recovered": "1092",
            "state": "Delhi",
            "statecode": "DL",
            "statenotes": ""
        },
        {
            "active": "1969",
            "confirmed": "2560",
            "deaths": "130",
            "deltaconfirmed": "0",
            "deltadeaths": "0",
            "deltarecovered": "0",
            "lastupdatedtime": "29/04/2020 21:02:47",
            "recovered": "461",
            "state": "Madhya Pradesh",
            "statecode": "MP",
            "statenotes": ""
        }
]

But this returns an array of size 0 for both states and num in componentWillMount() and getchartData() functions. I tried by manually entering all the enteries in labels and data and it works. Can anyone suggest how to pass the array data properly?

4
  • where is your fetch request?
    – Sachin
    Apr 30, 2020 at 6:56
  • @SachinKammar I have edited the question and added the fetch request. Hope this helps
    – zester
    Apr 30, 2020 at 7:30
  • 1
    There is no need to use state in the chart component. Why don't you use the passed props directly?
    – Josh
    Apr 30, 2020 at 7:39
  • if your chart is going to change with some parameters like date or something, you need to have it in a state.
    – Sachin
    Apr 30, 2020 at 8:36

1 Answer 1

1

Instead of componentWillMount you can add posts in componentDidMount.

import ReactDOM from "react-dom";
import Axios from 'axios';
import {Bar} from 'react-chartjs-2';
class Chart extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      chartData:props.chartData || {}
    }
  }

  static defaultProps = {
    displayTitle:true,
    displayLegend: true,
    legendPosition:'right',
    location:'City'
  }

  render(){
    return (
      <div className="chart">
        <Bar
          data={this.state.chartData}
          options={{
            title:{
              display:this.props.displayTitle,
              text:'State-Wise Bar Chart',
              fontSize:25
            },
            legend:{
              display:this.props.displayLegend,
              position:this.props.legendPosition
            }
          }}
        />
        </div>
    )
  }
}

class CaseList extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
             posts: [] ,
             chartData:{}
        }
    }

getchartData(states,num){
  console.log("states",states,"num",num)
this.setState({
        chartData:{
          labels: states,
        datasets: [
          {
            label:'No. of Positive Cases',
            data:num,
            backgroundColor:[

              'rgba(255,3,0,1)',
              'rgba(219,3,0,1)',
              'rgba(152,3,0,1)',
              'rgba(255,3,0,0.7)',
              'rgba(101,191,217,1)',
              'rgba(101,191,217,0.59)',
              'rgba(101,79,161,0.98)',
              'rgba(208,79,197,0.98)',
              'rgba(208,79,197,0.65)',
              'rgba(43,144,197,1)',
              ]
          }
        ]
      }
      },()=>{console.log(this.state.chartData)})
    }

componentDidMount() {
        Axios.get('https://api.covid19india.org/data.json')
        .then(response => {
            this.setState({posts:response.data.statewise});
            const posts = response.data.statewise
            var states=[]
            var num=[]

            for (var i=1;i<posts.length;i+=1) {
              states[i-1]=posts[i].state
              num[i-1]=posts[i].confirmed
          }
          this.getchartData(states,num);
            })
        .catch(error => {
            console.log(error)
        })
    }

render(){
return(
<div>
{Object.keys(this.state.chartData).length>0 &&<Chart chartData={this.state.chartData} />}
</div>
  )
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(
    <CaseList />,
  rootElement
);
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.