1

I am trying to plot pie chart using react and chartjs.

i am calling an API like this:-

const border ={
    border:'1px solid blue',
    borderRadius: '25px',
    padding:'15px',
    marginTop:'20px'
}

class ScreenView extends Component {



constructor(){
    super();
    this.state = {
        newUsers:'',
        allUsers:'',
        totalApplication:'',
        chartData:{},
            newuserstoday:'',
            candidatesOnliveAdvt:'',
            totalsignuptilltoday:'',
            genderDetails:{
                male:'',
                female:'',
                other:''
            }
        }

    }


componentDidMount(){

    const newChartData = {...this.state.chartData}

    let url4 ="http://localhost:7080/getGenderAgainstAdvt";

    getAllData(url4).then(
       response => this.setState({genderDetails:response.data},()=>{
        console.log("male gender count: "+this.state.genderDetails.male);
        console.log("female gender count: "+this.state.genderDetails.female);
        console.log("other gender count: "+this.state.genderDetails.others);
       })

    );

}
componentWillMount(){

    this.getChartData();
}

getChartData(){
    // Ajax calls here

    let maleCount = this.state.genderDetails.male;
    let femaleCount = this.state.genderDetails.female;
    let otherCount = this.state.genderDetails.other;

    console.log("male count is " +maleCount);


    this.setState({
      chartData:{
        labels: ['Male', 'Female', 'Other'],
        datasets:[
          {
            label:'Population',
            data:[
            maleCount,femaleCount,otherCount
            ],
            backgroundColor:[
              'rgba(255, 99, 132, 0.6)',
              'rgba(54, 162, 235, 0.6)',
              'rgba(255, 206, 86, 0.6)'
            ],
            borderWidth:1,
            hoverBorderWidth:3,
            hoverBorderColor:'green'
          }
        ]
      }
    });
  }


render(){
    return(
    <div>
        <div className="container">
            <div className="row" style={border}>
                <div className="col-sm-8">
                    <Chart chartData={this.state.chartData}/>
                </div>
            </div>
        </div>
    </div>
    );
}
}

export default ScreenView;

and my other component Chart looks like this:-

class Chart extends Component {

    constructor(props){
        super(props);
        this.state = {
          chartData:props.chartData
        }
        //console.log("chart data is here...."+ props.chartData.datasets[0].data[0].male);
      }

      static defaultProps = {
        displayTitle:true,
        displayLegend: true,
        legendPosition:'right',
        location:'16530-16536/2074-75'
      }

      render(){
        return (
          <div className="chart">
            <Pie
              data={this.state.chartData}
              options={{
                title:{
                  display:this.props.displayTitle,
                  text:'Pie Chart for Advertisement Code '+this.props.location,
                  fontSize:25
                },
                legend:{
                  display:this.props.displayLegend,
                  position:this.props.legendPosition
                }
              }}
            />
          </div>
        )
      }
}

my API returns very simple JSON which looks like this:-

{
    "male": 74433,
    "female": 51442,
    "others": 183
}

i need to fetch this API data and plot the pie chart according to it. my problem here is i cannot send the API returned data to chart dataset.

if i send some manual data to the chart i.e

datasets:[
          {
            label:'Population',
            data:[
           12345,54758,2154
            ],
}]

then it successfully plots data. but when now i have to use API fetched data instead of manually inserted data. how can i do it ?

update:-

my chart component was not receiving data. so i changed this.state.chartData to this.props.chartData and it half working. half working in a sense that i am now able to plot the chart but it only plots two given value out of three.

please see photos.

enter image description here

enter image description here

1 Answer 1

1

Just use the props data directly to render the chart like this:

<Pie
    data={this.props.chartData}
    ...
    ...

Every time your parent ScreenView fetch new data, that data will be sent down to the child Chart component and it will re-render it

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please try with a bigger other value, comparing it to the others it's percentage would be less than one. Chartjs may not draw if it's below 1%
ohh!! this might be the reason but this is real time data so adding high value manually won't make sense.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.