summaryrefslogtreecommitdiff
path: root/src/modules/home/hooks.ts
blob: 5c22bc6503d6536575aa77970884ce478536146d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import * as React from 'react';

import * as connAPI from '~/api/connections';
import prettyBytes from '~/misc/pretty-bytes';
import { ClashAPIConfig } from '~/types';

const { useCallback, useEffect, useState } = React;

export function useConnectionSummary(apiConfig: ClashAPIConfig) {
  const [state, setState] = useState({
    upTotal: '0 B',
    dlTotal: '0 B',
    connNumber: 0,
    mUsage: '0 B',
  });

  const read = useCallback(
    ({ downloadTotal, uploadTotal, connections, memory }) => {
      setState({
        upTotal: prettyBytes(uploadTotal),
        dlTotal: prettyBytes(downloadTotal),
        connNumber: connections ? connections.length : 0,
        mUsage: prettyBytes(memory),
      });
    },
    [setState]
  );

  useEffect(() => {
    return connAPI.fetchData(apiConfig, read, () => {
      /* noop */
    });
  }, [apiConfig, read]);

  return state;
}