useResultsMode.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {useCallback, useMemo} from 'react';
  2. import type {Location} from 'history';
  3. import {decodeScalar} from 'sentry/utils/queryString';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import {useNavigate} from 'sentry/utils/useNavigate';
  6. interface Options {
  7. location: Location;
  8. navigate: ReturnType<typeof useNavigate>;
  9. }
  10. export type ResultMode = 'samples' | 'aggregate';
  11. export function useResultMode(): [ResultMode, (newMode: ResultMode) => void] {
  12. const location = useLocation();
  13. const navigate = useNavigate();
  14. const options = {location, navigate};
  15. return useResultModeImpl(options);
  16. }
  17. function useResultModeImpl({
  18. location,
  19. navigate,
  20. }: Options): [ResultMode, (newMode: ResultMode) => void] {
  21. const resultMode: ResultMode = useMemo(() => {
  22. const rawMode = decodeScalar(location.query.mode);
  23. if (rawMode === 'aggregate') {
  24. return 'aggregate' as const;
  25. }
  26. return 'samples' as const;
  27. }, [location.query.mode]);
  28. const setResultMode = useCallback(
  29. (newMode: ResultMode) => {
  30. navigate({
  31. ...location,
  32. query: {
  33. ...location.query,
  34. mode: newMode,
  35. },
  36. });
  37. },
  38. [location, navigate]
  39. );
  40. return [resultMode, setResultMode];
  41. }