useCreateSavedSearch.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {SavedSearch, SavedSearchType, SavedSearchVisibility} from 'sentry/types';
  2. import {
  3. setApiQueryData,
  4. useMutation,
  5. UseMutationOptions,
  6. useQueryClient,
  7. } from 'sentry/utils/queryClient';
  8. import 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. };