ShareLink.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import React, {
  2. useState, useCallback,
  3. } from 'react';
  4. import useSWR from 'swr';
  5. import { useTranslation } from 'react-i18next';
  6. import { toastSuccess, toastError } from '~/client/util/apiNotification';
  7. import { apiv3Delete } from '~/client/util/apiv3-client';
  8. import { useCurrentPageId } from '~/stores/context';
  9. import { useSWRxSharelink } from '~/stores/share-link';
  10. import ShareLinkForm from './ShareLinkForm';
  11. import ShareLinkList from './ShareLinkList';
  12. const ShareLink = (): JSX.Element => {
  13. const { t } = useTranslation();
  14. const [isOpenShareLinkForm, setIsOpenShareLinkForm] = useState<boolean>(false);
  15. const { data: currentPageId } = useCurrentPageId();
  16. const { data, mutate } = useSWRxSharelink(currentPageId);
  17. const toggleShareLinkFormHandler = useCallback(() => {
  18. setIsOpenShareLinkForm(prev => !prev);
  19. mutate();
  20. }, [mutate]);
  21. const deleteAllLinksButtonHandler = useCallback(async() => {
  22. try {
  23. const res = await apiv3Delete('/share-links/', { relatedPage: currentPageId });
  24. const count = res.data.n;
  25. toastSuccess(t('toaster.remove_share_link', { count }));
  26. mutate();
  27. }
  28. catch (err) {
  29. toastError(err);
  30. }
  31. }, [mutate, currentPageId, t]);
  32. const deleteLinkById = useCallback(async(shareLinkId) => {
  33. try {
  34. const res = await apiv3Delete(`/share-links/${shareLinkId}`);
  35. const { deletedShareLink } = res.data;
  36. toastSuccess(t('toaster.remove_share_link_success', { shareLinkId: deletedShareLink._id }));
  37. mutate();
  38. }
  39. catch (err) {
  40. toastError(err);
  41. }
  42. }, [mutate, t]);
  43. return (
  44. <div className="container p-0" data-testid="share-link-management">
  45. <h3 className="grw-modal-head d-flex pb-2">
  46. { t('share_links.share_link_list') }
  47. <button className="btn btn-danger ml-auto " type="button" onClick={deleteAllLinksButtonHandler}>{t('delete_all')}</button>
  48. </h3>
  49. <div>
  50. <ShareLinkList
  51. shareLinks={data == null ? [] : data}
  52. onClickDeleteButton={deleteLinkById}
  53. />
  54. <button
  55. className="btn btn-outline-secondary d-block mx-auto px-5"
  56. type="button"
  57. onClick={toggleShareLinkFormHandler}
  58. >
  59. {isOpenShareLinkForm ? t('Close') : t('New')}
  60. </button>
  61. {isOpenShareLinkForm && <ShareLinkForm onCloseForm={toggleShareLinkFormHandler} />}
  62. </div>
  63. </div>
  64. );
  65. };
  66. export default ShareLink;