useSelectedDurationAggregate.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. type Query = {
  8. aggregate: string;
  9. };
  10. // TODO: Type more strictly, these should be limited to only valid aggregate
  11. // functions
  12. type Result = [string, (string) => void];
  13. export function useSelectedDurationAggregate(): Result {
  14. const [previouslySelectedAggregate, setPreviouslySelectedAggregate] =
  15. useLocalStorageState(KEY, DEFAULT_DURATION_AGGREGATE);
  16. const setSelectedAggregate = aggregate => {
  17. setPreviouslySelectedAggregate(aggregate);
  18. browserHistory.push({
  19. ...location,
  20. query: {
  21. ...location.query,
  22. aggregate,
  23. },
  24. });
  25. };
  26. const availableAggregates = useAvailableDurationAggregates();
  27. const location = useLocation<Query>();
  28. let selectedAggregate = decodeScalar(
  29. location.query.aggregate,
  30. previouslySelectedAggregate
  31. );
  32. if (!availableAggregates.includes(selectedAggregate)) {
  33. selectedAggregate = DEFAULT_DURATION_AGGREGATE;
  34. }
  35. return [selectedAggregate, setSelectedAggregate];
  36. }
  37. const KEY = 'performance-database-default-aggregation-function';