useSampleFields.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. interface Options {
  7. location: Location;
  8. navigate: ReturnType<typeof useNavigate>;
  9. }
  10. export type Field = string;
  11. export function useSampleFields(): [Field[], (fields: Field[]) => void] {
  12. const location = useLocation();
  13. const navigate = useNavigate();
  14. const options = {location, navigate};
  15. return useSampleFieldsImpl(options);
  16. }
  17. function useSampleFieldsImpl({
  18. location,
  19. navigate,
  20. }: Options): [Field[], (fields: Field[]) => void] {
  21. const sampleFields = useMemo(() => {
  22. const fields = decodeList(location.query.field);
  23. if (fields.length) {
  24. return fields;
  25. }
  26. return ['id', 'project', 'span.op', 'span.description', 'span.duration', 'timestamp'];
  27. }, [location.query.field]);
  28. const setSampleFields = useCallback(
  29. (fields: Field[]) => {
  30. navigate({
  31. ...location,
  32. query: {
  33. ...location.query,
  34. field: fields,
  35. },
  36. });
  37. },
  38. [location, navigate]
  39. );
  40. return [sampleFields, setSampleFields];
  41. }