I am trying to create a class based component in react that fetches a dataset and labels from my endpoint and then displays it in a graph based on chart.js.
But I have issues with state management as both the data and labels array are returned from my endpoint, but never displayed in the graph. When I log out values for
var labelSet = this.state.labels;
var dataSet = this.state.data;
console.log(labelSet)
console.log(dataSet)
Then nothing is displayed. I suspect it's poor understanding of state management in React from my side. That the component is rendering the graph with empty values because fetch hasn't finished, but somehow updated state values aren't re-rendering the component. What am I doing wrong?
import React, { Component } from 'react';
import Chart from 'chart.js/auto';
export default class LineChart extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
labels: []
};
}
chartRef = React.createRef();
componentDidMount() {
var productId = this.props.productId;
fetch('http://myendpoint/product/' + productId)
.then((response) => response.json())
.then(res => {
this.setState({ data: res.data });
this.setState({ labels: res.labels });
});
// THESE ARE NOT SET
var labelSet = this.state.labels;
var dataSet = this.state.data;
const ctx = this.chartRef.current.getContext("2d");
new Chart(ctx, {
type: "line",
data: {
labels: labelSet,
datasets: [{
data: dataSet,
label: productId,
borderColor: "#3e95cd",
backgroundColor: "#7bb6dd",
fill: false,
}
]
},
});
}
render() {
return (
<div>
<canvas id="myChart" ref={this.chartRef} />
</div>
)
}
}