Files
HealthCarePregnant/pcm-platform/patient-app/src/lib/useAutoRefresh.ts
T
2026-06-18 09:48:05 +08:00

44 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useRef } from 'react';
interface Options {
/** 轮询间隔(毫秒)。默认 20s。 */
intervalMs?: number;
/** 是否启用。默认 true。 */
enabled?: boolean;
}
/**
* 多端数据一致同步(T-8.5):以单一后端为真源,前端通过
* - 窗口 focus / 标签可见(visibilitychange
* - 可见时定时轮询
* 触发静默刷新,使本端近实时收敛到其他端(孕妇/家属/医护/运营)的改动。
*
* 注:V1 为"拉取式"近实时;实时推送(WebSocket/SSE)列入 V2。
* 仅在页面可见时轮询,避免后台无谓请求。
*/
export function useAutoRefresh(refresh: () => void, options?: Options): void {
const intervalMs = options?.intervalMs ?? 20000;
const enabled = options?.enabled ?? true;
const saved = useRef(refresh);
useEffect(() => {
saved.current = refresh;
}, [refresh]);
useEffect(() => {
if (!enabled) return;
const refreshIfVisible = (): void => {
if (document.visibilityState === 'visible') saved.current();
};
const onFocus = (): void => saved.current();
window.addEventListener('focus', onFocus);
document.addEventListener('visibilitychange', refreshIfVisible);
const id = window.setInterval(refreshIfVisible, intervalMs);
return () => {
window.removeEventListener('focus', onFocus);
document.removeEventListener('visibilitychange', refreshIfVisible);
window.clearInterval(id);
};
}, [intervalMs, enabled]);
}