grafana/public/app/plugins/datasource/grafana-azure-monitor-datasource/utils/useLastError.ts
Josh Hunt 9a7c10cffe
AzureMonitor: display errors from requests for the dropdowns (#31921)
* AzureMonitor: display errors from requests for the dropdowns

* switch to array of errors, using just the last one

* unify error object

* move files into utils

* TESTS

* fix tests
2021-03-24 12:06:55 +00:00

39 lines
1.2 KiB
TypeScript

import { useState, useCallback, useMemo } from 'react';
import { AzureMonitorErrorish } from '../types';
import messageFromError from './messageFromError';
type SourcedError = [string, AzureMonitorErrorish];
export default function useLastError() {
const [errors, setErrors] = useState<SourcedError[]>([]);
// Handles errors from any child components that request data to display their options
const addError = useCallback((errorSource: string, error: AzureMonitorErrorish | undefined) => {
setErrors((errors) => {
const errorsCopy = [...errors];
const index = errors.findIndex(([vSource]) => vSource === errorSource);
// If there's already an error, remove it. If we're setting a new error
// below, we'll move it to the front
if (index > -1) {
errorsCopy.splice(index, 1);
}
// And then add the new error to the top of the array. If error is defined, it was already
// removed above.
if (error) {
errorsCopy.unshift([errorSource, error]);
}
return errorsCopy;
});
}, []);
const errorMessage = useMemo(() => {
const recentError = errors[0];
return recentError && messageFromError(recentError[1]);
}, [errors]);
return [errorMessage, addError] as const;
}