0

I have a simple Scatter plot using ChartJS with React. The scatter plot in general has the ability connecting lines between the single datapoints by setting the option 'showLine' in the datasets. I want to have a button to toggle this option (turn showLines on/off). Unfortunately this doesn't work.

If showLines is true in the initalDataSet the change to false doesn't do anything. If showLines is false in the initalDataSet changing it to true crashes ChartJS with the following error:

Uncaught TypeError: line is null

This is a simple example of the problem described:

import React, {
  useEffect,
  useReducer,
} from "react";
import { Scatter } from "react-chartjs-2";
import Chart from "chart.js/auto";

const initalDataSet = {
  datasets: [
    {
      label: "dataset1",
      data: [
        {
          x: 1,
          y: 10,
        },
        {
          x: 3,
          y: 15,
        },
        {
          x: 5,
          y: 5,
        },
        {
          x: 7,
          y: 8,
        },
      ],
      borderColor: "red",
      showLine: false,
    },
    {
      label: "dataset2",
      data: [
        {
          x: 2,
          y: 4,
        },
        {
          x: 4,
          y: 6,
        },
        {
          x: 6,
          y: 12,
        },
        {
          x: 8,
          y: 18,
        },
        {
          x: 10,
          y: 10,
        },
        {
          x: 12,
          y: 15,
        },
        {
          x: 14,
          y: 5,
        },
        {
          x: 16,
          y: 8,
        },
      ],
      borderColor: "blue",
      showLine: false,
    },
  ],
};

const processData = (state, action) => {
  switch (action.type) {
    case "TOGGLE_LINE":
      return {
        ['datasets']: state.datasets.map((item) => ({
          ...item,
          showLine: (!item['showLine']),
        })),
      };
    default:
      return state;
  }
};

function App() {
  const [plotData, dispatch] = useReducer(processData, initalDataSet);

  useEffect(() => {
    console.log("debug --->", { datasets: Object.values(plotData) });
  }, [plotData]);

  return (
    <div className="App">
      <header className="App-header">
        <button
          onClick={() => {
            dispatch({ type: "TOGGLE_LINE" });
          }}
        >
          Toggle Line View
        </button>
        <Scatter data={plotData} />
      </header>
    </div>
  );
}

export default App;

I think it must have something to do with the rerendering of the ChartJS component, but I have no idea how to solve it. Does anyone have an idea how to do this?

Thanks!

don
  • 11
  • 2
  • you'll find a running example here: https://stackblitz.com/edit/react-hdhjmn?file=src/App.js – don Oct 05 '22 at 16:13

1 Answers1

0

A possible solution/workaround for this bug can be found here.

colinD
  • 1,641
  • 1
  • 20
  • 22
don
  • 11
  • 2