useSelectedDurationAggregate.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import {browserHistory} from 'react-router';
  2. import {decodeScalar} from 'sentry/utils/queryString';
  3. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import {DEFAULT_DURATION_AGGREGATE} from 'sentry/views/performance/database/settings';
  6. import {useAvailableDurationAggregates} from 'sentry/views/performance/database/useAvailableDurationAggregates';
  7. import type {Aggregate} from 'sentry/views/starfish/types';
  8. type Query = {
  9. aggregate: string;
  10. };
  11. type Result = [Aggregate, (string) => void];
  12. export function useSelectedDurationAggregate(): Result {
  13. const [previouslySelectedAggregate, setPreviouslySelectedAggregate] =
  14. useLocalStorageState(KEY, DEFAULT_DURATION_AGGREGATE);
  15. const setSelectedAggregate = aggregate => {
  16. setPreviouslySelectedAggregate(aggregate);
  17. browserHistory.push({
  18. ...location,
  19. query: {
  20. ...location.query,
  21. aggregate,
  22. },
  23. });
  24. };
  25. const availableAggregates = useAvailableDurationAggregates();
  26. const location = useLocation<Query>();
  27. const aggregateFromURL = decodeScalar(
  28. location.query.aggregate,
  29. previouslySelectedAggregate
  30. );
  31. const selectedAggregate = isAnAvailableAggregate(aggregateFromURL, availableAggregates)
  32. ? aggregateFromURL
  33. : DEFAULT_DURATION_AGGREGATE;
  34. return [selectedAggregate, setSelectedAggregate];
  35. }
  36. function isAnAvailableAggregate(
  37. maybeAggregate: string,
  38. availableAggregates: Aggregate[]
  39. ): maybeAggregate is Aggregate {
  40. // Manually widen `availableAggregates` to allow the comparison to string
  41. return (availableAggregates as unknown as string[]).includes(
  42. maybeAggregate as Aggregate
  43. );
  44. }
  45. const KEY = 'performance-database-default-aggregation-function';