Reputation: 1336
I'm trying to work with chartjs-2 in order to render a bar chart with data. Here is my code:
import React from "react";
import { Bar, Line, Pie } from "react-chartjs-2";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
chartData: {
labels: ["Nike", "Adidas", "Louis", "Champion", "Yeezy", "Versace"],
datasets: [
{
label: "Sales",
data: [34, 24, 4, 10, 18, 9],
backgroundColor: [
"rgba(255, 99, 132, 0.6)",
"rgba(54, 162, 235, 0.6)",
"rgba(255, 206, 86, 0.6)",
"rgba(75, 192, 192, 0.6)",
"rgba(153, 102, 255, 0.6)",
"rgba(255, 159, 64, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
}
]
}
};
}
setChartData(labels1, data1) {
//Pull from API here
this.setState({
chartData: {
labels: labels1,
datasets: [
{
label: "Sales",
data: data1,
backgroundColor: [
"rgba(255, 99, 132, 0.6)",
"rgba(54, 162, 235, 0.6)",
"rgba(255, 206, 86, 0.6)",
"rgba(75, 192, 192, 0.6)",
"rgba(153, 102, 255, 0.6)",
"rgba(255, 159, 64, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
}
]
}
});
return this.state.chartData;
}
render() {
var data1 = [4, 4, 14, 10, 16, 9]
var label1 = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth"]
console.log(() => this.setChartData(label1, data1))
return (
<Bar
data = {() => this.setChartData.bind(this, label1, data1)}
width = {100}
height = {75}
options = {{
legend: {
display: !this.props.displayLegend
}
}}/>
);
}
Whenever I run this, you can see the grid, but there are no bars (supposed to be a bar graph). If I replace the the data
in the render()
method with this.state.chartData
instead of () => this.setChartData.bind(this, label1, data1)
, it displays the chart that was created in the constructer but I want it to display the chart that was created in the setChartData
method. Any help would be greatly appreciated. Thanks!
Upvotes: 0
Views: 216
Reputation: 156
The render()
method should be a pure function, which means that it should not directly change the component state. You should either change your state in a lifecycle method (for example, componentDidMount()
) or a custom method (event handler) that you invoke yourself at some point in the render.
Here is a CodeSandbox demonstrating this idea.
I recommend going through the lifecycle methods and figuring out which one fits your purpose best.
Upvotes: 1