usePanelSave: Fix success/error notifications (#74454)

This commit is contained in:
kay delaney 2023-09-08 14:57:07 +01:00 committed by GitHub
parent 315a43da93
commit cca2905ddf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 40 deletions

View File

@ -1,18 +1,8 @@
import { createErrorNotification, createSuccessNotification } from '../../core/copy/appNotification';
import { AppNotification } from '../../types';
import { PanelModel } from '../dashboard/state';
import { addLibraryPanel, updateLibraryPanel } from './state/api';
import { LibraryElementDTO } from './types';
export function createPanelLibraryErrorNotification(message: string): AppNotification {
return createErrorNotification(message);
}
export function createPanelLibrarySuccessNotification(message: string): AppNotification {
return createSuccessNotification(message);
}
export async function saveAndRefreshLibraryPanel(panel: PanelModel, folderUid: string): Promise<LibraryElementDTO> {
const panelSaveModel = toPanelSaveModel(panel);
const savedPanel = await saveOrUpdateLibraryPanel(panelSaveModel, folderUid);

View File

@ -1,50 +1,31 @@
import { useEffect } from 'react';
import useAsyncFn from 'react-use/lib/useAsyncFn';
import { isFetchError } from '@grafana/runtime';
import { notifyApp } from 'app/core/actions';
import { useAppNotification } from 'app/core/copy/appNotification';
import { t } from 'app/core/internationalization';
import { PanelModel } from 'app/features/dashboard/state';
import { useDispatch } from 'app/types';
import {
createPanelLibraryErrorNotification,
createPanelLibrarySuccessNotification,
saveAndRefreshLibraryPanel,
} from '../utils';
import { saveAndRefreshLibraryPanel } from '../utils';
export const usePanelSave = () => {
const dispatch = useDispatch();
const notifyApp = useAppNotification();
const [state, saveLibraryPanel] = useAsyncFn(async (panel: PanelModel, folderUid: string) => {
try {
return await saveAndRefreshLibraryPanel(panel, folderUid);
const libEl = await saveAndRefreshLibraryPanel(panel, folderUid);
notifyApp.success(t('library-panels.save.success', 'Library panel saved'));
return libEl;
} catch (err) {
if (isFetchError(err)) {
err.isHandled = true;
throw new Error(err.data.message);
notifyApp.error(
t('library-panels.save.error', 'Error saving library panel: "{{errorMsg}}"', {
errorMsg: err.message ?? err.data.message,
})
);
}
throw err;
}
}, []);
useEffect(() => {
if (state.error) {
const errorMsg = state.error.message;
dispatch(
notifyApp(
createPanelLibraryErrorNotification(
t('library-panels.save.error', 'Error saving library panel: "{{errorMsg}}"', { errorMsg })
)
)
);
}
if (state.value) {
dispatch(
notifyApp(createPanelLibrarySuccessNotification(t('library-panels.save.success', 'Library panel saved')))
);
}
}, [dispatch, state]);
return { state, saveLibraryPanel };
};