useDeleteSavedSearch.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  2. import {t} from 'sentry/locale';
  3. import type {SavedSearch} from 'sentry/types/group';
  4. import type {UseMutationOptions} from 'sentry/utils/queryClient';
  5. import {
  6. getApiQueryData,
  7. setApiQueryData,
  8. useMutation,
  9. useQueryClient,
  10. } from 'sentry/utils/queryClient';
  11. import type RequestError from 'sentry/utils/requestError/requestError';
  12. import useApi from 'sentry/utils/useApi';
  13. import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
  14. type DeleteSavedSearchVariables = {
  15. id: string;
  16. orgSlug: string;
  17. };
  18. type DeleteSavedSearchResponse = unknown;
  19. type DeleteSavedSearchContext = {
  20. previousSavedSearches?: SavedSearch[];
  21. };
  22. type Options = UseMutationOptions<
  23. DeleteSavedSearchResponse,
  24. RequestError,
  25. DeleteSavedSearchVariables,
  26. DeleteSavedSearchContext
  27. >;
  28. export const useDeleteSavedSearchOptimistic = (
  29. incomingOptions: Omit<Options, 'mutationFn'> = {}
  30. ) => {
  31. const api = useApi({persistInFlight: true});
  32. const queryClient = useQueryClient();
  33. const options: Options = {
  34. ...incomingOptions,
  35. mutationFn: ({orgSlug, id}) => {
  36. return api.requestPromise(`/organizations/${orgSlug}/searches/${id}/`, {
  37. method: 'DELETE',
  38. });
  39. },
  40. onMutate: async variables => {
  41. await queryClient.cancelQueries({
  42. queryKey: makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
  43. });
  44. const previousSavedSearches = getApiQueryData<SavedSearch[]>(
  45. queryClient,
  46. makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug})
  47. );
  48. setApiQueryData(
  49. queryClient,
  50. makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
  51. oldData => {
  52. if (!Array.isArray(oldData)) {
  53. return oldData;
  54. }
  55. return oldData.filter(search => search?.id !== variables.id);
  56. }
  57. );
  58. incomingOptions.onMutate?.(variables);
  59. return {previousSavedSearches};
  60. },
  61. onError: (error, variables, context) => {
  62. addErrorMessage(t('Failed to delete saved search.'));
  63. if (context) {
  64. setApiQueryData(
  65. queryClient,
  66. makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
  67. context.previousSavedSearches
  68. );
  69. }
  70. incomingOptions.onError?.(error, variables, context);
  71. },
  72. };
  73. return useMutation(options);
  74. };