aboutsummaryrefslogtreecommitdiff
path: root/users/ryan/modules/simple-bar/simple-bar-source/lib/hooks/use-widget-refresh.js
blob: cf79515d9561b5c673f9e8d0ec536f55721a45d8 (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
37
import * as Uebersicht from "uebersicht";

const { React } = Uebersicht;

/**
 * Custom hook to refresh a widget at a specified frequency.
 *
 * @param {boolean} active - Flag indicating whether the widget is active.
 * @param {Function} getter - Function to fetch or update the widget data.
 * @param {number} refreshFrequency - Frequency in milliseconds to refresh the widget.
 */
export default function useWidgetRefresh(active, getter, refreshFrequency) {
  const abortableGetter = React.useCallback(
    (signal) => {
      if (!active || signal.aborted) return;
      getter();
    },
    [active, getter],
  );

  React.useEffect(() => {
    const controller = new AbortController();
    if (active) {
      abortableGetter(controller.signal);
      const interval = setInterval(
        () => abortableGetter(controller.signal),
        refreshFrequency,
      );
      return () => {
        controller.abort();
        clearInterval(interval);
      };
    } else {
      controller.abort();
    }
  }, [active, abortableGetter, refreshFrequency]);
}