mirror of
https://github.com/grafana/grafana.git
synced 2025-09-22 22:33:51 +08:00

* wip: new metrics query editor * prepend subscriptions to url path * remove duplicated setQueryValue file * add tests for new metrics query editor * wip start extracting resource field into a shared component * fix query editor test * fix up backend tests * move azure monitor specific getters to azure_monitor_datasource * use existing useAsyncState hook * extract useAsyncState into separate file * add datahooks tests * extract resource field component * cleanup * clarify variable names * remove logs query specific resource field component * add url_builder test * add azure_monitor_datasources tests * address comments * add types * pass resourceUri to resource field component * add test to check we reset the query fields when changing resources
25 lines
785 B
TypeScript
25 lines
785 B
TypeScript
import { useEffect, useMemo, useState } from 'react';
|
|
|
|
export function useAsyncState<T>(asyncFn: () => Promise<T>, setError: Function, dependencies: unknown[]) {
|
|
// Use the lazy initial state functionality of useState to assign a random ID to the API call
|
|
// to track where errors come from. See useLastError.
|
|
const [errorSource] = useState(() => Math.random());
|
|
const [value, setValue] = useState<T>();
|
|
|
|
const finalValue = useMemo(() => value ?? [], [value]);
|
|
|
|
useEffect(() => {
|
|
asyncFn()
|
|
.then((results) => {
|
|
setValue(results);
|
|
setError(errorSource, undefined);
|
|
})
|
|
.catch((err) => {
|
|
setError(errorSource, err);
|
|
});
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, dependencies);
|
|
|
|
return finalValue;
|
|
}
|