use-on-template-button-clicked.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { useCallback, useState } from 'react';
  2. import { useRouter } from 'next/router';
  3. import { createPage, exist } from '~/client/services/page-operation';
  4. import { LabelType } from '~/interfaces/template';
  5. export const useOnTemplateButtonClicked = (
  6. currentPagePath?: string,
  7. ): {
  8. onClickHandler: (label: LabelType) => Promise<void>,
  9. isPageCreating: boolean
  10. } => {
  11. const router = useRouter();
  12. const [isPageCreating, setIsPageCreating] = useState(false);
  13. const onClickHandler = useCallback(async(label: LabelType) => {
  14. try {
  15. setIsPageCreating(true);
  16. const path = currentPagePath == null || currentPagePath === '/'
  17. ? `/${label}`
  18. : `${currentPagePath}/${label}`;
  19. const params = {
  20. isSlackEnabled: false,
  21. slackChannels: '',
  22. grant: 4,
  23. // grant: currentPage?.grant || 1,
  24. // grantUserGroupId: currentPage?.grantedGroup?._id,
  25. };
  26. const res = await exist(JSON.stringify([path]));
  27. if (!res.pages[path]) {
  28. await createPage(path, '', params);
  29. }
  30. router.push(`${path}#edit`);
  31. }
  32. catch (err) {
  33. throw err;
  34. }
  35. finally {
  36. setIsPageCreating(false);
  37. }
  38. }, [currentPagePath, router]);
  39. return { onClickHandler, isPageCreating };
  40. };