useDashboardSave.tsx 2.5 KB

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