How to convert server side Json data into react-google-chart format in Reactjs

Viewed 506

I have the following output coming from my backend

[
    {
        "_id": null,
        "counts": [
            {
                "department": "Cleaning",
                "number": 1
            },
            {
                "department": "Engineering",
                "number": 2
            },
            {
                "department": "Transportation",
                "number": 1
            }
        ]
    }
]

I would like to convert the following data into google chart format and consequently display it on a pie Chart in reactjs.

This is my first time of working with google-charts, i really have no idea how to do the conversion. From what i read online, I could actually do something like this

class ChartPie extends React.Component {
state={
  data:[]
}
componentDidMount(){
  
axios.get(`/api/v1/employee/departCount`)
.then(({data}) => { // destructure data from response object
    // {department,number} from data
    const restructuredData = data.map(({department, number}) => 
        [department,number])

    this.setState({data: restructuredData});
})
.catch(function (error) {
  console.log(error);
})
}

if this where to be the case, then my other challenge will be how to make use of the new state inside the google chart API

 render() {
    return (
      <div>
      <Chart
  width={'500px'}
  height={'300px'}
  chartType="PieChart"
  loader={<div>Loading Chart</div>}
  data={[
  
  // how do I add the new state ?
  ]}
  options={{
    title: 'Work data',
    is3D: true,
  }}

I would appreciate any help whatsoever.

1 Answers
Related