forked from FOSS/Steam-Panel
v 3.0.3
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function usePolling(
|
||||
callback: () => void | Promise<void>,
|
||||
intervalMs: number,
|
||||
enabled = true,
|
||||
) {
|
||||
const cbRef = useRef(callback);
|
||||
cbRef.current = callback;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
cbRef.current();
|
||||
const id = setInterval(() => cbRef.current(), intervalMs);
|
||||
return () => clearInterval(id);
|
||||
}, [intervalMs, enabled]);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function useSSE<T>(
|
||||
url: string,
|
||||
onMessage: (data: T) => void,
|
||||
enabled = true,
|
||||
) {
|
||||
const cbRef = useRef(onMessage);
|
||||
cbRef.current = onMessage;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const es = new EventSource(url);
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
cbRef.current(JSON.parse(e.data));
|
||||
} catch { /* ignore parse errors */ }
|
||||
};
|
||||
es.onerror = () => {
|
||||
es.close();
|
||||
};
|
||||
|
||||
return () => es.close();
|
||||
}, [url, enabled]);
|
||||
}
|
||||
Reference in New Issue
Block a user