bananajoey88
bananajoey88

Reputation: 49

React Chart.js is not rendering lines when state changes

I am using React Chart.js V2 and I am trying to update my chart when the state changes. However it is only rendering the y-labels on the left side and is not drawing the lines. The dataset and label syntax is completely fine (see the image). If i take the console logged result and take it as the initial chart js state value it works fine, but still doesn't update on state change.

Dataset image

This is my code:

import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

const chartOptions = {
  responsive: true,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  plugins: {
    title: {
      display: true,
      text: 'Chart.js Line Chart - Multi Axis',
    },
  },
  scales: {
    x: {
      ticks: {
        maxTicksLimit: 6
      }
    }
  }
};

export default function Home({ ranking }) {
  const refreshChart() => {
    ...
    console.log({
      datasets,
      labels: dateLabels
    })
    setChartData({
      datasets,
      labels: dateLabels
    })
  }

  useEffect(() => {
    if (!statisticsLoading)
      refreshChart()
  }, [statisticsTimeSpan, statisticsLoading])


    return (
        ...
        <Line
            className="mb-4"
            options={chartOptions}
            data={chartData}
            redraw
        />
    )
}

Upvotes: 0

Views: 124

Answers (1)

bananajoey88
bananajoey88

Reputation: 49

I have noticed that I provided the wrong format for the labels to react-chartjs-2...

For the "labels" property i provided an array inside an array which is wrong. It has to be only one array.

Upvotes: 0

Related Questions