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
);
Source:stackexchange.com