refactor: rewrite useSubscription with RQ and use it in UsageDataInformation
This commit is contained in:
@@ -1,11 +1,28 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { DateTime } from 'luxon';
|
||||
import * as React from 'react';
|
||||
|
||||
import useFormatMessage from './useFormatMessage';
|
||||
import api from 'helpers/api';
|
||||
|
||||
function transform(subscription) {
|
||||
const nextBillDate = subscription?.nextBillDate;
|
||||
const nextBillDateTitleDateObject = DateTime.fromISO(nextBillDate);
|
||||
const formattedNextBillDateTitle = nextBillDateTitleDateObject.isValid
|
||||
? nextBillDateTitleDateObject.toFormat('LLL dd, yyyy')
|
||||
: nextBillDate;
|
||||
|
||||
return {
|
||||
...subscription,
|
||||
nextBillDate: formattedNextBillDateTitle,
|
||||
};
|
||||
}
|
||||
|
||||
export default function useSubscription() {
|
||||
const formatMessage = useFormatMessage();
|
||||
const location = useLocation();
|
||||
const state = location.state;
|
||||
const checkoutCompleted = state?.checkoutCompleted;
|
||||
const [isPolling, setIsPolling] = React.useState(false);
|
||||
|
||||
const { data, isLoading: isSubscriptionLoading } = useQuery({
|
||||
queryKey: ['subscription'],
|
||||
@@ -16,23 +33,38 @@ export default function useSubscription() {
|
||||
|
||||
return data;
|
||||
},
|
||||
refetchInterval: isPolling ? 1000 : false,
|
||||
});
|
||||
|
||||
const subscription = data?.data;
|
||||
|
||||
const hasSubscription = !!subscription?.status;
|
||||
|
||||
React.useEffect(
|
||||
function pollDataUntilSubscriptionIsCreated() {
|
||||
if (checkoutCompleted && !hasSubscription) {
|
||||
setIsPolling(true);
|
||||
}
|
||||
},
|
||||
[checkoutCompleted, hasSubscription],
|
||||
);
|
||||
|
||||
React.useEffect(
|
||||
function stopPollingWhenSubscriptionIsCreated() {
|
||||
if (checkoutCompleted && hasSubscription) {
|
||||
setIsPolling(false);
|
||||
}
|
||||
},
|
||||
[checkoutCompleted, hasSubscription],
|
||||
);
|
||||
|
||||
const cancellationEffectiveDate = subscription?.cancellationEffectiveDate;
|
||||
|
||||
const hasCancelled = !!cancellationEffectiveDate;
|
||||
|
||||
if (isSubscriptionLoading || !hasCancelled) return null;
|
||||
|
||||
const cancellationEffectiveDateObject = DateTime.fromISO(
|
||||
cancellationEffectiveDate,
|
||||
);
|
||||
|
||||
return {
|
||||
message: formatMessage('subscriptionCancelledAlert.text', {
|
||||
date: cancellationEffectiveDateObject.toFormat('DDD'),
|
||||
}),
|
||||
cancellationEffectiveDate: cancellationEffectiveDateObject,
|
||||
data: transform(subscription),
|
||||
};
|
||||
}
|
||||
|
Reference in New Issue
Block a user