hooks.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { useCallback, useState } from 'react';
  2. import { useRouter } from 'next/router';
  3. import { createPage, exist } from '~/client/services/page-operation';
  4. import { toastError } from '~/client/util/toastr';
  5. import { EditorMode, useEditorMode } from '~/stores/ui';
  6. export const useOnNewButtonClicked = (
  7. currentPagePath?: string,
  8. isLoading?: boolean,
  9. ): {
  10. onClickHandler: () => Promise<void>,
  11. isPageCreating: boolean
  12. } => {
  13. const router = useRouter();
  14. const [isPageCreating, setIsPageCreating] = useState(false);
  15. const { mutate: mutateEditorMode } = useEditorMode();
  16. const onClickHandler = useCallback(async() => {
  17. if (isLoading) return;
  18. try {
  19. setIsPageCreating(true);
  20. const response = await createPage({
  21. parentPath: currentPagePath,
  22. optionalParentPath: '/',
  23. });
  24. await router.push(`/${response.page._id}#edit`);
  25. mutateEditorMode(EditorMode.Editor);
  26. }
  27. catch (err) {
  28. toastError(err);
  29. }
  30. finally {
  31. setIsPageCreating(false);
  32. }
  33. }, [currentPagePath, isLoading, mutateEditorMode, router]);
  34. return { onClickHandler, isPageCreating };
  35. };
  36. export const useOnTodaysButtonClicked = (
  37. todaysPath: string | null,
  38. ): {
  39. onClickHandler: () => Promise<void>,
  40. isPageCreating: boolean
  41. } => {
  42. const router = useRouter();
  43. const [isPageCreating, setIsPageCreating] = useState(false);
  44. const { mutate: mutateEditorMode } = useEditorMode();
  45. const onClickHandler = useCallback(async() => {
  46. if (todaysPath == null) {
  47. return;
  48. }
  49. try {
  50. setIsPageCreating(true);
  51. const res = await exist(JSON.stringify([todaysPath]));
  52. if (!res.pages[todaysPath]) {
  53. await createPage({ path: todaysPath });
  54. }
  55. await router.push(`${todaysPath}#edit`);
  56. mutateEditorMode(EditorMode.Editor);
  57. }
  58. catch (err) {
  59. toastError(err);
  60. }
  61. finally {
  62. setIsPageCreating(false);
  63. }
  64. }, [mutateEditorMode, router, todaysPath]);
  65. return { onClickHandler, isPageCreating };
  66. };