useSelectedSavedSearch.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {useMemo} from 'react';
  2. import {t} from 'sentry/locale';
  3. import type {SavedSearch} from 'sentry/types';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import useOrganization from 'sentry/utils/useOrganization';
  6. import {useParams} from 'sentry/utils/useParams';
  7. import {useFetchSavedSearchesForOrg} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
  8. const PINNED_SEARCH_NAME = t('My Default Search');
  9. // Uses the saved search ID in the URL and the cached response to return
  10. // the selected saved search object
  11. export const useSelectedSavedSearch = (): SavedSearch | null => {
  12. const organization = useOrganization();
  13. const location = useLocation();
  14. const params = useParams();
  15. const {data: savedSearches} = useFetchSavedSearchesForOrg(
  16. {orgSlug: organization.slug},
  17. {notifyOnChangeProps: ['data']}
  18. );
  19. const selectedSearchId: string | undefined = params.searchId;
  20. // If there's no direct saved search being requested (via URL route)
  21. // *AND* there's no query in URL, then check if there is pinned search
  22. const selectedSavedSearch =
  23. !selectedSearchId &&
  24. (location.query.query === null || location.query.query === undefined)
  25. ? savedSearches?.find(search => search.isPinned)
  26. : savedSearches?.find(({id}) => id === selectedSearchId);
  27. return useMemo(
  28. () =>
  29. selectedSavedSearch?.isPinned
  30. ? {
  31. ...selectedSavedSearch,
  32. name: PINNED_SEARCH_NAME,
  33. }
  34. : selectedSavedSearch ?? null,
  35. [selectedSavedSearch]
  36. );
  37. };