All files / src/hooks/common/graph useGraph.ts

0% Statements 0/26
0% Branches 0/5
0% Functions 0/3
0% Lines 0/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                                                                                           
import { useState, useEffect, useMemo, useRef } from "react";
import ReactECharts from "echarts-for-react";
import { handleLegendClick as handleLegendClickUtil } from "../../../utils/common/graph/handleLegendClick";
import { processData } from "../../../utils/common/graph/processData";
import { getChartOptions } from "../../../utils/common/graph/getChartOptions";
 
const useGraph = (result: any) => {
  const [chartOptions, setChartOptions] = useState({});
  const [showGraph, setShowGraph] = useState(false);
  const [selectedLegends, setSelectedLegends] = useState({});
  const chartRef = useRef<ReactECharts>(null);
 
  let tsData = result?.timeseries?.labeled_metric_timeseries;
 
  useEffect(() => {
    if (tsData && tsData.length > 0 && tsData[0].datapoints) {
      const { sortedTSData, tsLabels, data, unit } = processData(
        tsData,
        result,
      );
 
      const initialLegendsState = tsLabels.reduce((acc: any, label: string) => {
        acc[label] = true;
        return acc;
      }, {});
      setSelectedLegends(initialLegendsState);
 
      const updatedChartOptions = getChartOptions(
        sortedTSData,
        tsLabels,
        data,
        unit,
        initialLegendsState,
      );
      setChartOptions(updatedChartOptions);
      setShowGraph(true);
    } else {
      setChartOptions({});
      setShowGraph(false);
    }
    (chartRef.current as any)?.resize();
  }, [tsData]);
 
  const handleLegendClick = handleLegendClickUtil(
    selectedLegends,
    setSelectedLegends,
    setChartOptions,
  );
 
  return { chartOptions, showGraph, handleLegendClick, chartRef };
};
 
export default useGraph;