existingOrCreate.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import {useEffect} from 'react';
  2. import LoadingIndicator from 'sentry/components/loadingIndicator';
  3. import {useApiQuery} from 'sentry/utils/queryClient';
  4. import {useNavigate} from 'sentry/utils/useNavigate';
  5. import useOrganization from 'sentry/utils/useOrganization';
  6. import {makeAlertsPathname} from 'sentry/views/alerts/pathnames';
  7. import {CombinedAlertType, type UptimeAlert} from '../../types';
  8. /**
  9. * When no uptime alert rules exist, takes the user to create a new alert. If
  10. * multiple rules exists redirects them to the listing page. If only a single
  11. * rule exists, tak them to edit that alert rule.
  12. *
  13. * This route is used for docs and marketing purposes.
  14. */
  15. export default function ExistingOrCreate() {
  16. const organization = useOrganization();
  17. const navigate = useNavigate();
  18. const {data: existingRules, isPending} = useApiQuery<UptimeAlert[]>(
  19. [
  20. `/organizations/${organization.slug}/combined-rules/`,
  21. {query: {alertType: CombinedAlertType.UPTIME}},
  22. ],
  23. {staleTime: 300}
  24. );
  25. useEffect(() => {
  26. if (isPending || !existingRules) {
  27. return;
  28. }
  29. // Has one single alert rule
  30. if (existingRules.length === 1) {
  31. const url = makeAlertsPathname({
  32. path: `/uptime-rules/${existingRules[0]?.projectSlug}/${existingRules[0]?.id}/`,
  33. organization,
  34. });
  35. navigate(url, {replace: true});
  36. return;
  37. }
  38. // Has multiple existing alert rules
  39. if (existingRules.length > 1) {
  40. const url = makeAlertsPathname({
  41. path: `/rules/`,
  42. organization,
  43. });
  44. navigate(
  45. {
  46. pathname: url,
  47. query: {
  48. alertType: CombinedAlertType.UPTIME,
  49. },
  50. },
  51. {replace: true}
  52. );
  53. return;
  54. }
  55. // No alert rules, create a new one
  56. const url = makeAlertsPathname({
  57. path: `/new/uptime/`,
  58. organization,
  59. });
  60. navigate(url, {replace: true});
  61. }, [existingRules, isPending, navigate, organization]);
  62. return <LoadingIndicator />;
  63. }