useHeartbeat.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import {useState} from 'react';
  2. import {Project, SessionApiResponse, SessionFieldWithOperation} from 'sentry/types';
  3. import {useQuery} from 'sentry/utils/queryClient';
  4. import {getCount} from 'sentry/utils/sessions';
  5. import useOrganization from 'sentry/utils/useOrganization';
  6. const DEFAULT_POLL_INTERVAL = 5000;
  7. type Props = {
  8. project?: Project;
  9. };
  10. export function useHeartbeat({project}: Props) {
  11. const organization = useOrganization();
  12. const [firstErrorReceived, setFirstErrorReceived] = useState(false);
  13. const [firstTransactionReceived, setFirstTransactionReceived] = useState(false);
  14. const [hasSession, setHasSession] = useState(false);
  15. const {isLoading: eventLoading} = useQuery<Project>(
  16. [`/projects/${organization.slug}/${project?.slug}/`],
  17. {
  18. staleTime: 0,
  19. refetchInterval: DEFAULT_POLL_INTERVAL,
  20. enabled: !!project && !firstErrorReceived, // Fetch only if the project is available and we have not yet received an error,
  21. onSuccess: data => {
  22. setFirstErrorReceived(!!data.firstEvent);
  23. // When an error is received, a transaction is also received
  24. setFirstTransactionReceived(!!data.firstTransactionEvent);
  25. },
  26. }
  27. );
  28. const {isLoading: sessionLoading} = useQuery<SessionApiResponse>(
  29. [
  30. `/organizations/${organization.slug}/sessions/`,
  31. {
  32. query: {
  33. project: project?.id,
  34. statsPeriod: '24h',
  35. field: [SessionFieldWithOperation.SESSIONS],
  36. },
  37. },
  38. ],
  39. {
  40. staleTime: 0,
  41. refetchInterval: DEFAULT_POLL_INTERVAL,
  42. enabled: !!project && !(hasSession || firstTransactionReceived), // Fetch only if the project is available and we if a connection to Sentry was not yet established,
  43. onSuccess: data => {
  44. const hasHealthData =
  45. getCount(data.groups, SessionFieldWithOperation.SESSIONS) > 0;
  46. setHasSession(hasHealthData);
  47. },
  48. }
  49. );
  50. return {
  51. hasSession,
  52. firstErrorReceived,
  53. firstTransactionReceived,
  54. eventLoading,
  55. sessionLoading,
  56. };
  57. }