useDataset.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {useCallback, useMemo} from 'react';
  2. import type {Location} from 'history';
  3. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  4. import {decodeScalar} from 'sentry/utils/queryString';
  5. import {useLocation} from 'sentry/utils/useLocation';
  6. import {useNavigate} from 'sentry/utils/useNavigate';
  7. interface Options {
  8. location: Location;
  9. navigate: ReturnType<typeof useNavigate>;
  10. allowRPC?: boolean;
  11. }
  12. interface UseDatasetOptions {
  13. allowRPC?: boolean;
  14. }
  15. export function useDataset(
  16. options?: UseDatasetOptions
  17. ): [DiscoverDatasets, (dataset: DiscoverDatasets) => void] {
  18. const location = useLocation();
  19. const navigate = useNavigate();
  20. return useDatasetImpl({location, navigate, allowRPC: options?.allowRPC});
  21. }
  22. function useDatasetImpl({
  23. location,
  24. navigate,
  25. allowRPC,
  26. }: Options): [DiscoverDatasets, (dataset: DiscoverDatasets) => void] {
  27. const dataset: DiscoverDatasets = useMemo(() => {
  28. const rawDataset = decodeScalar(location.query.dataset);
  29. if (rawDataset === 'spansIndexed') {
  30. return DiscoverDatasets.SPANS_INDEXED;
  31. }
  32. if (allowRPC && rawDataset === 'spansRpc') {
  33. return DiscoverDatasets.SPANS_EAP_RPC;
  34. }
  35. return DiscoverDatasets.SPANS_EAP;
  36. }, [location.query.dataset, allowRPC]);
  37. const setDataset = useCallback(
  38. (newDataset: DiscoverDatasets) => {
  39. navigate({
  40. ...location,
  41. query: {
  42. ...location.query,
  43. dataset: newDataset,
  44. },
  45. });
  46. },
  47. [location, navigate]
  48. );
  49. return [dataset, setDataset];
  50. }