0

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>
            )
    }
}
Kasper Hansen
  • 6,307
  • 21
  • 70
  • 106
  • You are not waiting for the `fetch` to complete before you update the state. `fetch` is async, so it will not complete by the time you get to setting those variables – smac89 Dec 12 '21 at 19:21
  • Fastest solution should be moving your chart creation into where you set the state with the new data. If that data isn't going to change though, do you even need to store it in state? If it does, then you want to use [componentDidUpdate](https://reactjs.org/docs/react-component.html#componentdidupdate) and instantiate your graph there. Also combine your setState calls into one. – DCardenas Dec 12 '21 at 19:43

0 Answers0