grafana/public/app/features/dashboard/components/PanelEditor/usePanelLatestData.ts
Dominik Prokop e5d21461a0
Refactor panel inspector (#24480)
* Inspect: Should not subscribe to transformed data

* PQR- allow controll whether or not field overrides and transformations should be applied

* UI for inspector data options

* fix

* Null check fix

* Refactor PanelInspector

* TS fix

* Merge fix

* fix test

* Update public/app/features/dashboard/components/Inspector/InspectDataTab.tsx

Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com>

* review batch 1

* Update API of usePanelLatestData

* css

* review batch 2

* Update usePanelLatestData hook

Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com>
2020-06-18 14:31:30 +02:00

47 lines
1.5 KiB
TypeScript

import { DataQueryError, LoadingState, PanelData } from '@grafana/data';
import { useEffect, useRef, useState } from 'react';
import { PanelModel } from '../../state';
import { Unsubscribable } from 'rxjs';
import { GetDataOptions } from '../../state/PanelQueryRunner';
interface UsePanelLatestData {
data?: PanelData;
error?: DataQueryError;
isLoading: boolean;
hasSeries: boolean;
}
/**
* Subscribes and returns latest panel data from PanelQueryRunner
*/
export const usePanelLatestData = (panel: PanelModel, options: GetDataOptions): UsePanelLatestData => {
const querySubscription = useRef<Unsubscribable>(null);
const [latestData, setLatestData] = useState<PanelData>();
useEffect(() => {
querySubscription.current = panel
.getQueryRunner()
.getData(options)
.subscribe({
next: data => setLatestData(data),
});
return () => {
if (querySubscription.current) {
querySubscription.current.unsubscribe();
}
};
/**
* Adding separate options to dependencies array to avoid additional hook for comparing previous options with current.
* Otherwise, passing different references to the same object may cause troubles.
*/
}, [panel, options.withFieldConfig, options.withTransforms]);
return {
data: latestData,
error: latestData && latestData.error,
isLoading: latestData ? latestData.state === LoadingState.Loading : true,
hasSeries: latestData ? !!latestData.series : false,
};
};