Cleanup - unused files / unused exports / duplicate exports
[ProtonMail-WebClient.git] / packages / components / hooks / useLastSubscriptionEnd.ts
bloba57379ecddaf6cc558ff868dd6371b2039d94d9e
1 import { useEffect, useState } from 'react';
3 import { useUser } from '@proton/account/user/hooks';
4 import { useLoading } from '@proton/hooks';
5 import useIsMounted from '@proton/hooks/useIsMounted';
6 import type { LatestSubscription } from '@proton/payments';
7 import { getLastCancelledSubscription } from '@proton/shared/lib/api/payments';
9 import useApi from './useApi';
11 let promise: Promise<LatestSubscription> | undefined;
13 const useLastSubscriptionEnd = (): [latestSubscription: number, loading: boolean] => {
14     const api = useApi();
15     const [loading, withLoading] = useLoading();
16     const [{ isPaid }] = useUser();
17     const [latestSubscription, setLatestSubscription] = useState<number>(0);
18     const isMounted = useIsMounted();
20     useEffect(() => {
21         if (isPaid) {
22             setLatestSubscription(0);
23             return;
24         }
25         const run = async () => {
26             try {
27                 if (!promise) {
28                     promise = api<LatestSubscription>(getLastCancelledSubscription());
29                 }
31                 const { LastSubscriptionEnd = 0 } = await promise;
33                 if (isMounted()) {
34                     setLatestSubscription(LastSubscriptionEnd || 0);
35                 }
36             } catch (e) {
37                 // Ignore
38             } finally {
39                 // Reset promise to allow a new request
40                 promise = undefined;
41             }
42         };
43         void withLoading(run());
44     }, [isPaid]);
46     return [latestSubscription, loading];
49 export default useLastSubscriptionEnd;