Search code examples
reactjschart.jsreact-chartjs

Unable to display data in Bar Chart using react-chart-2


I am trying to use react-chartjs-2 the React wrapper for chart.js. I am not sure why I am unable to display a Bar Chart. It might be how I'm setting the state for the data prop. My data that is returned from the API I want to display in the chart is in this format:

[{packets: 14132, bytes: 743572434}, {packets: 10848, bytes: 824102247}, {packets: 7412, bytes: 1391125317}, {packets: 3978, bytes: 9107974}, ... , {packets: 4228, bytes: 8781508}]

I want to update the data prop in my barchart state with this but am not sure if I'm doing it right. When I console.log this.state.barchart.datasets.data in the render() it will initially comes up as an empty array, and then it gets filled with the appropriate data. When I log this.state.barchart.labels it always comes up with the expected labels. Since the labels is getting set but the data isn't, I'm not sure what the problem is. I also don't know if I'm setting the conditional to display the Bar Chart itself because sometimes this.state.barchart.datasets.data.length throws an error: TypeError: Cannot read property 'length' of undefined.

Here is my component:

class Devices extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      barchart: {
        labels: [],
        datasets: [
          {
            label: "byte count",
            backgroundColor: "rgba(75,192,192,1)",
            borderColor: "rgba(0,102,204,1)",
            borderWidth: 2,
            data: [],
          },
        ],
      }
  }
    
  componentDidMount(){
      all_hours = ["12:00 am", "1:00 am " ... "12:00 pm"]
      fetch(API_URL)
      .catch((error) => console.error("Error: ", error))
      .then((data) => {
        var barchart = {...this.state.barchart}
        barchart.labels = all_hours // update the labels 
        barchart.datasets.data = data.map(x => { return x["bytes"]}) // update the data
        this.setState({barchart})
    })

  render(){
    return(
        <div className="Line">
            {typeof(this.state.barchart.datasets.data) !== "undefined" 
              && this.state.barchart.datasets.data.length > 0? (
            <Bar
              data = {this.state.barchart}
              options={{
                title: {
                  display: true,
                  text: "Total Byte Count Per Hour",
                  fontSize: 20,
                },
                legend: {
                  display: true,
                  position: "right",
                },
              }}
            />
            ) : (
              <div>Loading...</div>
            )}
          </div>
    )
  }
}

Solution

  • The problem is that you're adding the data at the wrong place.

    barchart.datasets.data = data.map(x => { return x["bytes"]})
    

    barchart.datasets is an array that contains a single dataset in your case. Therefore, this should be rewritten as follows:

    barchart.datasets[0].data = data.map(x => { return x["bytes"]})
    

    This can be simplified in the following way:

    barchart.datasets[0].data = data.map(x => x["bytes"])