usePinSearch.tsx 2.0 KB

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