2020-06-18 20:31:30 +08:00
|
|
|
import { DataQueryError, LoadingState, PanelData } from '@grafana/data';
|
2020-04-23 01:21:48 +08:00
|
|
|
import { useEffect, useRef, useState } from 'react';
|
|
|
|
import { PanelModel } from '../../state';
|
|
|
|
import { Unsubscribable } from 'rxjs';
|
2020-05-25 20:05:43 +08:00
|
|
|
import { GetDataOptions } from '../../state/PanelQueryRunner';
|
2020-04-23 01:21:48 +08:00
|
|
|
|
2020-06-18 20:31:30 +08:00
|
|
|
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 => {
|
2020-04-23 01:21:48 +08:00
|
|
|
const querySubscription = useRef<Unsubscribable>(null);
|
2020-06-18 20:31:30 +08:00
|
|
|
const [latestData, setLatestData] = useState<PanelData>();
|
2020-04-23 01:21:48 +08:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
querySubscription.current = panel
|
|
|
|
.getQueryRunner()
|
2020-05-25 20:05:43 +08:00
|
|
|
.getData(options)
|
2020-04-23 01:21:48 +08:00
|
|
|
.subscribe({
|
|
|
|
next: data => setLatestData(data),
|
|
|
|
});
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
if (querySubscription.current) {
|
|
|
|
querySubscription.current.unsubscribe();
|
|
|
|
}
|
|
|
|
};
|
2020-06-18 20:31:30 +08:00
|
|
|
/**
|
|
|
|
* 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]);
|
2020-04-23 01:21:48 +08:00
|
|
|
|
2020-06-18 20:31:30 +08:00
|
|
|
return {
|
|
|
|
data: latestData,
|
|
|
|
error: latestData && latestData.error,
|
|
|
|
isLoading: latestData ? latestData.state === LoadingState.Loading : true,
|
|
|
|
hasSeries: latestData ? !!latestData.series : false,
|
|
|
|
};
|
2020-04-23 01:21:48 +08:00
|
|
|
};
|