usePanelSave.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { useEffect } from 'react';
  2. import { useDispatch } from 'react-redux';
  3. import useAsyncFn from 'react-use/lib/useAsyncFn';
  4. import { notifyApp } from 'app/core/actions';
  5. import { PanelModel } from 'app/features/dashboard/state';
  6. import {
  7. createPanelLibraryErrorNotification,
  8. createPanelLibrarySuccessNotification,
  9. saveAndRefreshLibraryPanel,
  10. } from '../utils';
  11. export const usePanelSave = () => {
  12. const dispatch = useDispatch();
  13. const [state, saveLibraryPanel] = useAsyncFn(async (panel: PanelModel, folderId: number) => {
  14. try {
  15. return await saveAndRefreshLibraryPanel(panel, folderId);
  16. } catch (err) {
  17. err.isHandled = true;
  18. throw new Error(err.data.message);
  19. }
  20. }, []);
  21. useEffect(() => {
  22. if (state.error) {
  23. dispatch(notifyApp(createPanelLibraryErrorNotification(`Error saving library panel: "${state.error.message}"`)));
  24. }
  25. if (state.value) {
  26. dispatch(notifyApp(createPanelLibrarySuccessNotification('Library panel saved')));
  27. }
  28. }, [dispatch, state]);
  29. return { state, saveLibraryPanel };
  30. };