useCreateSavedSearch.tsx 1.6 KB

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