users/ryan/modules/simple-bar/simple-bar-source/lib/hooks/use-widget-refresh.js
592f73c2672474c09dedc5cac8e6fa857a7df92b
· 1.0 KB · 37 lines
raw
| 1 | import * as Uebersicht from "uebersicht"; |
| 2 | |
| 3 | const { React } = Uebersicht; |
| 4 | |
| 5 | /** |
| 6 | * Custom hook to refresh a widget at a specified frequency. |
| 7 | * |
| 8 | * @param {boolean} active - Flag indicating whether the widget is active. |
| 9 | * @param {Function} getter - Function to fetch or update the widget data. |
| 10 | * @param {number} refreshFrequency - Frequency in milliseconds to refresh the widget. |
| 11 | */ |
| 12 | export default function useWidgetRefresh(active, getter, refreshFrequency) { |
| 13 | const abortableGetter = React.useCallback( |
| 14 | (signal) => { |
| 15 | if (!active || signal.aborted) return; |
| 16 | getter(); |
| 17 | }, |
| 18 | [active, getter], |
| 19 | ); |
| 20 | |
| 21 | React.useEffect(() => { |
| 22 | const controller = new AbortController(); |
| 23 | if (active) { |
| 24 | abortableGetter(controller.signal); |
| 25 | const interval = setInterval( |
| 26 | () => abortableGetter(controller.signal), |
| 27 | refreshFrequency, |
| 28 | ); |
| 29 | return () => { |
| 30 | controller.abort(); |
| 31 | clearInterval(interval); |
| 32 | }; |
| 33 | } else { |
| 34 | controller.abort(); |
| 35 | } |
| 36 | }, [active, abortableGetter, refreshFrequency]); |
| 37 | } |