NextJS 13.4 app import 'chart.js/auto'; increase the bundle size

61 Views Asked by At

In my next app, following component used to display many charts. To working it fine I had to import chart.js/auto

Unless it gives following error

react-chartjs-2: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused

I need to import chart.js/auto dynamically and reduce the bundle size. Or import only necessary things.

Here is my code

import { ChartData, Chart as ChartJS } from 'chart.js';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Chart } from 'react-chartjs-2';
import 'chart.js/auto';

import { createGradient, getChartOptions, getColorsForPrices } from './PriceFluctuationChart.config';
import { PriceFluctuationChartProps } from './PriceFluctuationChart.types';

export function PriceFluctuationChart({ testID, prices }: PriceFluctuationChartProps) {
  const chartRef = useRef<ChartJS>(null);

  const [chartData, setChartData] = useState<ChartData<'line'>>({
    datasets: [],
  });

  useEffect(() => {
    const chart = chartRef.current;

    if (!chart) {
      return;
    }
    if (prices.length > 0) {
      // chart can not draw by only one value, so here duplicating same value
      if (prices.length === 1) {
        prices.push(prices[0]);
      }
      const chartData = {
        labels: prices,
        datasets: [{ data: prices, fill: false, borderColor: createGradient(chart.ctx, chart.chartArea, prices) }],
      };

      setChartData(chartData);
    }
  }, [prices]);

  const options = useMemo(() => getChartOptions(getColorsForPrices(prices)), [prices]);

  return <Chart data-testid={testID} type="line" options={options} data={chartData} ref={chartRef} />;
}
0

There are 0 best solutions below