I'm trying to push dynamic colors into my chart but I'm having difficulty doing so. In my state, I have the background color inside of an array of objects for my data sets. However, I'm unsure of how to push my dynamic colors into it.
Reason I need to push all these colors is because I'm eventually going to be pulling dynamic data from my database inside of my data sets so I decided to create random dynamic colors for the charts. The hard coded data are placeholders for now.
I read online that I can use Immutability Helpers to achieve pushing these colors inside the deep nested object but I'm having difficulty figuring it out.
Here is my code:
import React from 'react';
import reportsService from '../../services/reportsService';
import update from 'react-addons-update';
import {Bar, Line, Pie} from 'react-chartjs-2';
class Reportspage extends React.Component {
constructor(props){
super(props);
this.state = {
chartData: {
// Placeholder labels for now
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Population',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: []
}]
}
}
}
chartColors(){
let colors = [];
// Start with 100 random colors for now. If data increases, increase loop value
for(let i = 0; i < 100; i++) {
let r = Math.floor(Math.random() * 200);
let g = Math.floor(Math.random() * 200);
let b = Math.floor(Math.random() * 200);
let c = 'rgb(' + r + ', ' + g + ', ' + b + ')';
colors.push(c);
}
// How can I push these colors inside of my deep nested state?
this.setState({
chartData: update(this.state.chartData.datasets, {datasets: {$set: colors}})
})
}
async componentDidMount(){
this.chartColors();
const showReports = await reportsService.showDowntime();
console.log(showReports);
console.log(this.state);
}
render(){
return (
<div className="fluid-container">
<div className="container">
<h1>Reports</h1>
<div className="chartContainer">
<Bar
data={this.state.chartData}
options={{
maintainAspectRatio: false
}}
/>
</div>
</div>
</div>
)
}
}
export default Reportspage;