useCreateSavedSearch.tsx 1.7 KB

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