Cleanup - unused files / unused exports / duplicate exports
[ProtonMail-WebClient.git] / packages / components / hooks / useVPNLogicals.ts
blobaeb9981552e1721a95da5a3b85c216fdf67c603d
1 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
3 import { queryVPNLogicalServerInfo } from '@proton/shared/lib/api/vpn';
4 import type { Logical } from '@proton/shared/lib/vpn/Logical';
6 import useApi from './useApi';
7 import useCache from './useCache';
9 const useVPNLogicals = () => {
10     const api = useApi();
11     const mountedRef = useRef(true);
12     const cache = useCache();
13     const [state, setState] = useState<{
14         error?: Error;
15         result?: {
16             LogicalServers: Logical[];
17         };
18         loading: boolean;
19     }>(() => ({ result: cache.get('vpn-logicals')?.result, loading: false }));
21     const fetch = useCallback(async (maxAge = 0) => {
22         try {
23             const cachedValue = cache.get('vpn-logicals');
24             const time = new Date().getTime();
26             if (cachedValue?.time + maxAge >= time) {
27                 setState({ result: cachedValue?.result, loading: false });
29                 return;
30             }
32             if (cachedValue?.promise) {
33                 const result = await cachedValue?.promise;
34                 setState({ result, loading: false });
36                 return;
37             }
39             const promise = api(queryVPNLogicalServerInfo()) as Promise<{ LogicalServers: Logical[] }>;
40             cache.set('vpn-logicals', { promise });
41             const result = await promise;
42             cache.set('vpn-logicals', {
43                 result,
44                 time,
45             });
47             if (mountedRef.current) {
48                 setState({ result, loading: false });
49             }
50         } catch (e) {
51             cache.delete('vpn-logicals');
53             if (mountedRef.current) {
54                 setState({ error: e as Error, loading: false });
55             }
56         }
57     }, []);
59     useEffect(() => {
60         if (!cache.has('vpn-logicals')) {
61             fetch();
62         }
64         return () => {
65             mountedRef.current = false;
66         };
67     }, []);
69     return useMemo(
70         () => ({
71             ...state,
72             fetch,
73         }),
74         [state]
75     );
78 export default useVPNLogicals;