attachment.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useCallback } from 'react';
  2. import {
  3. IAttachment, Nullable, SWRResponseWithUtils, withUtils,
  4. } from '@growi/core';
  5. import useSWR from 'swr';
  6. import { apiGet, apiPost } from '~/client/util/apiv1-client';
  7. import { IResAttachmentList } from '~/interfaces/attachment';
  8. type Util = {
  9. remove(body: { attachment_id: string }): Promise<void>
  10. };
  11. type IDataAttachmentList = {
  12. attachments: IAttachment[]
  13. totalAttachments: number
  14. limit: number
  15. };
  16. export const useSWRxAttachments = (pageId?: Nullable<string>, pageNumber?: number): SWRResponseWithUtils<Util, IDataAttachmentList, Error> => {
  17. const shouldFetch = pageId != null && pageNumber != null;
  18. const fetcher = useCallback(async(endpoint) => {
  19. const res = await apiGet<IResAttachmentList>(endpoint, { pageId, pageNumber });
  20. return {
  21. attachments: res.data.paginateResult.docs,
  22. totalAttachments: res.data.paginateResult.totalDocs,
  23. limit: res.data.paginateResult.limit,
  24. };
  25. }, [pageId, pageNumber]);
  26. const swrResponse = useSWR(
  27. shouldFetch ? ['/attachments/list', pageId, pageNumber] : null,
  28. fetcher,
  29. );
  30. // Utils
  31. const remove = useCallback(async(body: { attachment_id: string }) => {
  32. const { mutate } = swrResponse;
  33. try {
  34. await apiPost('/attachments.remove', body);
  35. mutate();
  36. }
  37. catch (err) {
  38. throw err;
  39. }
  40. }, [swrResponse]);
  41. return withUtils<Util, IDataAttachmentList, Error>(swrResponse, { remove });
  42. };