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 = () => {
11 const mountedRef = useRef(true);
12 const cache = useCache();
13 const [state, setState] = useState<{
16 LogicalServers: Logical[];
19 }>(() => ({ result: cache.get('vpn-logicals')?.result, loading: false }));
21 const fetch = useCallback(async (maxAge = 0) => {
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 });
32 if (cachedValue?.promise) {
33 const result = await cachedValue?.promise;
34 setState({ result, loading: false });
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', {
47 if (mountedRef.current) {
48 setState({ result, loading: false });
51 cache.delete('vpn-logicals');
53 if (mountedRef.current) {
54 setState({ error: e as Error, loading: false });
60 if (!cache.has('vpn-logicals')) {
65 mountedRef.current = false;
78 export default useVPNLogicals;