useCreateSavedSearch.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type {
  2. SavedSearch,
  3. SavedSearchType,
  4. SavedSearchVisibility,
  5. } from 'sentry/types/group';
  6. import type {UseMutationOptions} from 'sentry/utils/queryClient';
  7. import {setApiQueryData, useMutation, useQueryClient} from 'sentry/utils/queryClient';
  8. import type RequestError from 'sentry/utils/requestError/requestError';
  9. import useApi from 'sentry/utils/useApi';
  10. import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
  11. type CreateSavedSearchVariables = {
  12. name: string;
  13. orgSlug: string;
  14. query: string;
  15. sort: string | null;
  16. type: SavedSearchType;
  17. visibility: SavedSearchVisibility;
  18. };
  19. type CreateSavedSearchResponse = SavedSearch;
  20. export const useCreateSavedSearch = (
  21. options: Omit<
  22. UseMutationOptions<
  23. CreateSavedSearchResponse,
  24. RequestError,
  25. CreateSavedSearchVariables
  26. >,
  27. 'mutationFn'
  28. > = {}
  29. ) => {
  30. const api = useApi();
  31. const queryClient = useQueryClient();
  32. return useMutation<CreateSavedSearchResponse, RequestError, CreateSavedSearchVariables>(
  33. {
  34. ...options,
  35. mutationFn: ({orgSlug, ...data}: CreateSavedSearchVariables) =>
  36. api.requestPromise(`/organizations/${orgSlug}/searches/`, {
  37. method: 'POST',
  38. data,
  39. }),
  40. onSuccess: (savedSearch, parameters, context) => {
  41. setApiQueryData(
  42. queryClient,
  43. makeFetchSavedSearchesForOrgQueryKey({orgSlug: parameters.orgSlug}),
  44. oldData => {
  45. if (!Array.isArray(oldData)) {
  46. return oldData;
  47. }
  48. return [savedSearch, ...oldData];
  49. }
  50. );
  51. options.onSuccess?.(savedSearch, parameters, context);
  52. },
  53. }
  54. );
  55. };