-
Notifications
You must be signed in to change notification settings - Fork 11.7k
/
useDashboardSave.tsx
73 lines (63 loc) · 2.58 KB
/
useDashboardSave.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { useEffect } from 'react';
import useAsyncFn from 'react-use/lib/useAsyncFn';
import { locationUtil } from '@grafana/data';
import { locationService, reportInteraction } from '@grafana/runtime';
import appEvents from 'app/core/app_events';
import { useAppNotification } from 'app/core/copy/appNotification';
import { contextSrv } from 'app/core/core';
import { updateDashboardName } from 'app/core/reducers/navBarTree';
import { DashboardModel } from 'app/features/dashboard/state';
import { saveDashboard as saveDashboardApiCall } from 'app/features/manage-dashboards/state/actions';
import { useDispatch } from 'app/types';
import { DashboardSavedEvent } from 'app/types/events';
import { SaveDashboardOptions } from './types';
const saveDashboard = async (saveModel: any, options: SaveDashboardOptions, dashboard: DashboardModel) => {
let folderId = options.folderId;
if (folderId === undefined) {
folderId = dashboard.meta.folderId ?? saveModel.folderId;
}
const result = await saveDashboardApiCall({ ...options, folderId, dashboard: saveModel });
// fetch updated access control permissions
await contextSrv.fetchUserPermissions();
return result;
};
export const useDashboardSave = (dashboard: DashboardModel) => {
const [state, onDashboardSave] = useAsyncFn(
async (clone: any, options: SaveDashboardOptions, dashboard: DashboardModel) =>
await saveDashboard(clone, options, dashboard),
[]
);
const dispatch = useDispatch();
const notifyApp = useAppNotification();
useEffect(() => {
if (state.error && !state.loading) {
notifyApp.error(state.error.message ?? 'Error saving dashboard');
}
if (state.value) {
dashboard.version = state.value.version;
dashboard.clearUnsavedChanges();
// important that these happen before location redirect below
appEvents.publish(new DashboardSavedEvent());
notifyApp.success('Dashboard saved');
reportInteraction(`grafana_dashboard_${dashboard.id ? 'saved' : 'created'}`, {
name: dashboard.title,
url: state.value.url,
});
const currentPath = locationService.getLocation().pathname;
const newUrl = locationUtil.stripBaseFromUrl(state.value.url);
if (newUrl !== currentPath) {
setTimeout(() => locationService.replace(newUrl));
}
if (dashboard.meta.isStarred) {
dispatch(
updateDashboardName({
id: dashboard.uid,
title: dashboard.title,
url: newUrl,
})
);
}
}
}, [dashboard, state, notifyApp, dispatch]);
return { state, onDashboardSave };
};