useSelectedSavedSearch.tsx 1.5 KB

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