usePinSearch.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  2. import {t} from 'sentry/locale';
  3. import {SavedSearch, SavedSearchType} 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 PinSavedSearchVariables = {
  9. orgSlug: string;
  10. query: string;
  11. sort: string | null;
  12. type: SavedSearchType;
  13. };
  14. type PinSavedSearchResponse = SavedSearch;
  15. export const usePinSearch = (
  16. options: Omit<
  17. UseMutationOptions<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>,
  18. 'mutationFn'
  19. > = {}
  20. ) => {
  21. const api = useApi();
  22. const queryClient = useQueryClient();
  23. return useMutation<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>({
  24. ...options,
  25. mutationFn: ({orgSlug, query, type, sort}) =>
  26. api.requestPromise(`/organizations/${orgSlug}/pinned-searches/`, {
  27. method: 'PUT',
  28. data: {query, type, sort},
  29. }),
  30. onSuccess: (savedSearch, variables, context) => {
  31. queryClient.setQueryData<SavedSearch[]>(
  32. makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
  33. oldData => {
  34. if (!Array.isArray(oldData)) {
  35. return oldData;
  36. }
  37. return [
  38. savedSearch,
  39. // Make sure we remove any existing pinned searches
  40. ...oldData.filter(search => !search.isPinned),
  41. ];
  42. }
  43. );
  44. addSuccessMessage(t('When you come back you’ll see this search by default.'));
  45. options.onSuccess?.(savedSearch, variables, context);
  46. },
  47. onError: (error, variables, context) => {
  48. addErrorMessage(t('Unable to set the default search.'));
  49. options.onError?.(error, variables, context);
  50. },
  51. });
  52. };