useDeleteGroupEventAttachment.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  2. import {t} from 'sentry/locale';
  3. import type {IssueAttachment} from 'sentry/types/group';
  4. import {
  5. getApiQueryData,
  6. setApiQueryData,
  7. useMutation,
  8. useQueryClient,
  9. } from 'sentry/utils/queryClient';
  10. import type RequestError from 'sentry/utils/requestError/requestError';
  11. import useApi from 'sentry/utils/useApi';
  12. import {makeFetchGroupEventAttachmentsQueryKey} from './useGroupEventAttachments';
  13. type DeleteGroupEventAttachmentVariables = Parameters<
  14. typeof makeFetchGroupEventAttachmentsQueryKey
  15. >[0] & {
  16. attachment: IssueAttachment;
  17. projectSlug: string;
  18. };
  19. type DeleteGroupEventAttachmentContext = {
  20. previous?: IssueAttachment[];
  21. };
  22. export function useDeleteGroupEventAttachment() {
  23. const api = useApi({persistInFlight: true});
  24. const queryClient = useQueryClient();
  25. return useMutation<
  26. unknown,
  27. RequestError,
  28. DeleteGroupEventAttachmentVariables,
  29. DeleteGroupEventAttachmentContext
  30. >({
  31. mutationFn: variables =>
  32. api.requestPromise(
  33. `/projects/${variables.orgSlug}/${variables.projectSlug}/events/${variables.attachment.event_id}/attachments/${variables.attachment.id}/`,
  34. {
  35. method: 'DELETE',
  36. }
  37. ),
  38. onMutate: async variables => {
  39. await queryClient.cancelQueries({
  40. queryKey: makeFetchGroupEventAttachmentsQueryKey(variables),
  41. });
  42. const previous = getApiQueryData<IssueAttachment[]>(
  43. queryClient,
  44. makeFetchGroupEventAttachmentsQueryKey(variables)
  45. );
  46. setApiQueryData<IssueAttachment[]>(
  47. queryClient,
  48. makeFetchGroupEventAttachmentsQueryKey(variables),
  49. oldData => {
  50. if (!Array.isArray(oldData)) {
  51. return oldData;
  52. }
  53. return oldData.filter(
  54. oldAttachment => oldAttachment.id !== variables.attachment.id
  55. );
  56. }
  57. );
  58. return {previous};
  59. },
  60. onSuccess: () => {
  61. addSuccessMessage(t('Attachment deleted'));
  62. },
  63. onError: (error, variables, context) => {
  64. addErrorMessage(
  65. error?.responseJSON?.detail
  66. ? (error.responseJSON.detail as string)
  67. : t('An error occurred while deleting the attachment')
  68. );
  69. if (context) {
  70. setApiQueryData(
  71. queryClient,
  72. makeFetchGroupEventAttachmentsQueryKey(variables),
  73. context.previous
  74. );
  75. }
  76. },
  77. });
  78. }