useProfileStats.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {useEffect, useState} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import {Client} from 'sentry/api';
  4. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  5. import {t} from 'sentry/locale';
  6. import {EventsStatsSeries, Organization, PageFilters, RequestState} from 'sentry/types';
  7. import {defined} from 'sentry/utils';
  8. import useApi from 'sentry/utils/useApi';
  9. import useOrganization from 'sentry/utils/useOrganization';
  10. type ProfileStatsResult = EventsStatsSeries;
  11. interface UseProfileStatsOptions {
  12. query: string;
  13. selection?: PageFilters;
  14. }
  15. export function useProfileStats({
  16. query,
  17. selection,
  18. }: UseProfileStatsOptions): RequestState<ProfileStatsResult> {
  19. const api = useApi();
  20. const organization = useOrganization();
  21. const [requestState, setRequestState] = useState<RequestState<ProfileStatsResult>>({
  22. type: 'initial',
  23. });
  24. useEffect(() => {
  25. if (!defined(selection)) {
  26. return undefined;
  27. }
  28. setRequestState({type: 'loading'});
  29. fetchProfileStats(api, organization, {
  30. query,
  31. selection,
  32. })
  33. .then(result => {
  34. setRequestState({
  35. type: 'resolved',
  36. data: result,
  37. });
  38. })
  39. .catch(err => {
  40. setRequestState({
  41. type: 'errored',
  42. error: t('Error: Unable to load profile stats'),
  43. });
  44. Sentry.captureException(err);
  45. });
  46. return () => api.clear();
  47. }, [api, organization, query, selection]);
  48. return requestState;
  49. }
  50. function fetchProfileStats(
  51. api: Client,
  52. organization: Organization,
  53. {
  54. query,
  55. selection,
  56. }: {
  57. query: string;
  58. selection: PageFilters;
  59. }
  60. ) {
  61. return api.requestPromise(`/organizations/${organization.slug}/profiling/stats/`, {
  62. method: 'GET',
  63. includeAllArgs: false,
  64. query: {
  65. query,
  66. project: selection.projects,
  67. environment: selection.environments,
  68. ...normalizeDateTimeParams(selection.datetime),
  69. },
  70. });
  71. }