usePinSearch.tsx 2.0 KB

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