Chartjs-Why chart renders after second click – react-chartjs-2

0👍

When you first click, you trigger a request for the data, but your component does not wait for that data before rendering.

I would recommend adding a condition to your return. This is how I would have done it without Redux (I’ve never used Redux)

return (  
  <div className="container">
    <div className="head" style={{'marginBottom': '30px'}}>
      <h2>Chart</h2>
      <div className="line" style={{"width": "900px"}}></div>
    </div>
    <div className="chart">
      {chartDataState.length > 0 ? 
      <Line
        data={chartDataState}
        options={{
          maintainAspectRatio: false,
          legend: {
            display: false,
          }
        }}
        height={400}
      />
      : <div>Loading...</div>}
    </div>
  </div>
);

Basically: you don’t want your component to render the chart before the data is returned.

Leave a comment