I have one Array that consist of one Key called Status it has two value 1 is good and other is bad i am using react-google-charts i upload my code below kindly check and help me
JSON:
[
{
Status: 'Good'
},
{
Status: 'Bad'
},
{
Status: 'Bad'
},
{
Status: 'Good'
},
{
Status: 'Good'
},
{
Status: 'Bad'
},
{
Status: 'Good'
}
]
My React Code:
import React from 'react';
import Chart from 'react-google-charts';
import axios from 'axios';
export default class chart extends Component {
constructor() {
super();
this.state = {
items: []
};
}
componentDidMount() {
axios.get('http://localhost:5000/items').then(response => this.setState({ items: response.data }));
}
render() {
return (
<div>
<Chart
width={'500px'}
height={'300px'}
chartType="PieChart"
loader={<div>Loading Chart</div>}
data={[['Task', 'Status of Items'], ['Good', 4], ['Bad', 3]]}
options={{
title: 'Item Status'
}}
rootProps={{ 'data-testid': '1' }}
/>
</div>
);
}
}
Currently i'm hardcoded the value here:
data={[
['Task', 'Status of Items'],
['Good', 4],
['Bad', 3],
]}
I want to add the no of good and bad on above code using API i try to find length of array but it didn't work it finds whole array value not either good or bad. kindly help me
First, you can reduce
to get the Good and Bad counts to a single JSON
and then use Object.entries
to get the required format as in an array.
Try like this
<Chart
width={'500px'}
height={'300px'}
chartType="PieChart"
loader={<div>Loading Chart</div>}
data={[
['Task', 'Status of Items'],
...Object.entries(
this.state.items.reduce((prevValue, currValue) => {
prevValue[currValue.Status] =
prevValue[currValue.Status] === undefined ? 1 : prevValue[currValue.Status] + 1;
return prevValue;
}, {})
)
]}
options={{
title: 'Item Status'
}}
rootProps={{ 'data-testid': '1' }}
/>
Code sandbox => https://codesandbox.io/s/busy-wind-1bizj?file=/src/App.js