usePreviewData.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import type {ReactElement} from 'react';
  2. import type {Organization} from 'sentry/types/organization';
  3. import {useApiQuery} from 'sentry/utils/queryClient';
  4. import type {Plan, PreviewData, Subscription} from 'getsentry/types';
  5. import type {Reservations} from './types';
  6. import useUpgradeNowParams from './useUpgradeNowParams';
  7. type Result =
  8. | {
  9. error: false;
  10. loading: true;
  11. plan: undefined;
  12. previewData: undefined;
  13. reservations: undefined;
  14. }
  15. | {
  16. error: false;
  17. loading: false;
  18. plan: Plan;
  19. previewData: PreviewData;
  20. reservations: Reservations;
  21. }
  22. | {
  23. error: true;
  24. loading: false;
  25. plan: undefined;
  26. previewData: undefined;
  27. reservations: undefined;
  28. };
  29. type Props = {
  30. children: (props: Result) => ReactElement;
  31. organization: Organization;
  32. subscription: Subscription;
  33. enabled?: boolean;
  34. };
  35. export default function usePreviewData({
  36. organization,
  37. subscription,
  38. enabled = true,
  39. }: Omit<Props, 'children'>): Result {
  40. const hasBillingAccess = organization.access?.includes('org:billing');
  41. const {plan, reservations} = useUpgradeNowParams({
  42. organization,
  43. subscription,
  44. enabled: enabled && hasBillingAccess,
  45. });
  46. const {
  47. isPending,
  48. isError,
  49. data: previewData,
  50. } = useApiQuery<PreviewData>(
  51. [
  52. `/customers/${organization.slug}/subscription/preview/`,
  53. {
  54. query: {
  55. ...reservations,
  56. plan: plan?.id,
  57. referrer: 'replay-am2-update-modal',
  58. },
  59. },
  60. ],
  61. {
  62. staleTime: 0,
  63. enabled: !!plan && !!reservations && hasBillingAccess && enabled,
  64. }
  65. );
  66. if (isError) {
  67. return {
  68. loading: false,
  69. error: true,
  70. plan: undefined,
  71. reservations: undefined,
  72. previewData: undefined,
  73. };
  74. }
  75. if (isPending || !plan || !reservations || !previewData) {
  76. return {
  77. loading: true,
  78. error: false,
  79. plan: undefined,
  80. reservations: undefined,
  81. previewData: undefined,
  82. };
  83. }
  84. return {
  85. loading: false,
  86. error: false,
  87. plan,
  88. previewData,
  89. reservations,
  90. };
  91. }