Files
co-lite/solvway-admin-portal/app/lib/hooks/usePolling.ts
T
ngqileandClaude Opus 5.5 1d5e792e3d feat: whatsapp portal proxy, client service and polling hook
Part of tasks 5.1/5.2 (not ticked): one catch-all proxy at /api/whatsapp (media
served with nosniff and a sandbox CSP), typed client calls, and usePolling that
pauses while the tab is hidden.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-02 11:03:56 +08:00

29 lines
1.0 KiB
TypeScript

import { useEffect, useRef } from "react";
/**
* Calls `fn` now, then every `ms` while the tab is visible, again when the tab shows, and whenever the
* optional window event fires. The latest `fn` is used without restarting the timer.
*/
// ponytail: polling (30 s list, 10 s thread); server-sent events if the delay ever matters.
export function usePolling(fn: () => void, ms: number, refreshEvent?: string, enabled = true) {
const latest = useRef(fn);
useEffect(() => {
latest.current = fn;
});
useEffect(() => {
if (!enabled) return;
const run = () => {
if (!document.hidden) latest.current();
};
run();
const id = window.setInterval(run, ms);
document.addEventListener("visibilitychange", run);
if (refreshEvent) window.addEventListener(refreshEvent, run);
return () => {
window.clearInterval(id);
document.removeEventListener("visibilitychange", run);
if (refreshEvent) window.removeEventListener(refreshEvent, run);
};
}, [ms, refreshEvent, enabled]);
}