useGroupBys.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import {useCallback, useMemo} from 'react';
  2. import type {Location} from 'history';
  3. import {decodeList} from 'sentry/utils/queryString';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import {useNavigate} from 'sentry/utils/useNavigate';
  6. import type {Field} from 'sentry/views/explore/hooks/useSampleFields';
  7. interface Options {
  8. location: Location;
  9. navigate: ReturnType<typeof useNavigate>;
  10. }
  11. type GroupBysResult = {
  12. groupBys: Field[];
  13. setGroupBys: (fields: Field[]) => void;
  14. };
  15. export function useGroupBys(): GroupBysResult {
  16. const location = useLocation();
  17. const navigate = useNavigate();
  18. const options = {location, navigate};
  19. return useGroupBysImpl(options);
  20. }
  21. function useGroupBysImpl({location, navigate}: Options): GroupBysResult {
  22. const groupBys = useMemo(() => {
  23. const rawGroupBys = decodeList(location.query.groupBy);
  24. if (rawGroupBys.length) {
  25. return rawGroupBys;
  26. }
  27. return [''];
  28. }, [location.query.groupBy]);
  29. const setGroupBys = useCallback(
  30. (newGroupBys: Field[]) => {
  31. navigate({
  32. ...location,
  33. query: {
  34. ...location.query,
  35. groupBy: newGroupBys,
  36. },
  37. });
  38. },
  39. [location, navigate]
  40. );
  41. return {
  42. groupBys,
  43. setGroupBys,
  44. };
  45. }