Chartjs-How do I mutate Chart.js data using React state?

1👍

You may be encountering issues because you are trying to shallow merge state with the useState hook. React does not support this. See this answer for more info.

If that does not solve your issue, have you looked into react-chartjs-2? You might be able to achieve what you want doing something like the following.

In your parent component (the one that contains the chart):

import { Bar } from "react-chartjs-2"; // import whatever chart type you need
...

const [userData, setUserData] = useState({
    labels: Object.keys(daysData),
    datasets: [
      {
        label: "Hours worked",
        data: Object.values(daysData),
        backgroundColor: "red",
        borderColor: "black",
        borderWidth: 2,
      },
    ],
  });

Then your handlers can be:

  const onShowWeeklyHandler = () => {
    setUserData({
      ...userData,
      datasets: {
        ...userData.datasets,
        labels: Object.keys(daysData),
        data: Object.values(daysData),
      },
    });
  };

  const onShowMonthlyHandler = () => {
    setUserData({
      ...userData,
      datasets: {
        ...userData.datasets,
        labels: Object.keys(monthsData),
        data: Object.values(monthsData),
      },
    });
  };

Finally:

return <Bar data={userData.datasets} />; // adapt for whatever chart type you need

Leave a comment