summaryrefslogtreecommitdiff
path: root/src/hooks/useLineChart.ts
blob: a3205aa067426137c28ba73a216d03afc1578864 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import type { ChartConfiguration } from 'chart.js';
import React from 'react';
import { commonChartOptions } from 'src/misc/chart';

const { useEffect } = React;

export default function useLineChart(
  chart: typeof import('chart.js').Chart,
  elementId: string,
  data: ChartConfiguration['data'],
  subscription: any,
  extraChartOptions = {}
) {
  useEffect(() => {
    const ctx = (document.getElementById(elementId) as HTMLCanvasElement).getContext('2d');
    const options = { ...commonChartOptions, ...extraChartOptions };
    const c = new chart(ctx, { type: 'line', data, options });
    const unsubscribe = subscription && subscription.subscribe(() => c.update());
    return () => {
      unsubscribe && unsubscribe();
      c.destroy();
    };
  }, [chart, elementId, data, subscription, extraChartOptions]);
}