4

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.

8SINS
  • 431
  • 2
  • 6
  • 16

1 Answers1

0

Here is some sample state should look like:

const data = [
  ["Element", "Density", { role: "style" }],
  ["Copper", 8.94, "#b87333"], // RGB value
  ["Silver", 10.49, "silver"], // English color name
  ["Gold", 19.3, "gold"],
  ["Platinum", 21.45, "color: #e5e4e2"] // CSS-style declaration
];

You need a couple of array manipulations to create a correct data state. Working sample: https://codesandbox.io/s/react-google-charts-column-chart-forked-spjmz?file=/src/index.js:577-845

Viet
  • 12,133
  • 2
  • 15
  • 21