useDeleteSavedSearch.tsx 2.3 KB

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