I am creating a dashboard app that fetches data from an endpoint and uses the setState method to assign variables from the JSON returned by the endpoint to state variables. When I make a change to state, some components like 'react-svg-gauge' will update but 'react-chartjs-2' does not update.
The below code is an example of how my state changes in my actual app. This example will display the correct value of the state variables in the chrome developer console but does not update the DOM accordingly.
import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';
class DoughnutExample extends Component {
state = {
data: {
labels: [
'Red',
'Green',
'Yellow'
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
],
hoverBackgroundColor: [
'#FF6384',
'#36A2EB',
'#FFCE56'
]
}]
}
}
componentDidMount() {
this.timer = setInterval(
() => this.increment(),
1000
)
}
componentWillUnmount() {
clearInterval(this.timer)
}
increment() {
let datacopy = Object.assign({}, this.state.data)
datacopy.datasets[0].data[0] = datacopy.datasets[0].data[0] + 10
console.log(datacopy.datasets[0].data[0])
this.setState({data: datacopy})
}
render(){
return(
<div>
<Doughnut data = {this.state.data}/>
</div>
)
}
}
export default DoughnutExample;
Am I using the lifecycle methods correctly? This code will update the value of the pie chart, the state variable but will not correctly render the DOM.