|
1 | 1 | import { useRevalidator } from "@remix-run/react"; |
2 | | -import { useEffect, useRef } from "react"; |
| 2 | +import { useInterval } from "./useInterval"; |
3 | 3 |
|
4 | 4 | type UseAutoRevalidateOptions = { |
5 | 5 | interval?: number; // in milliseconds |
6 | 6 | onFocus?: boolean; |
7 | 7 | disabled?: boolean; |
8 | 8 | }; |
9 | 9 |
|
| 10 | +/** |
| 11 | + * Re-runs the current route's loaders on a timer. |
| 12 | + * |
| 13 | + * Ticks are skipped while the tab is hidden. A backgrounded tab has no one watching it, |
| 14 | + * and at the default interval it would otherwise spend a working day accumulating |
| 15 | + * thousands of chances to catch a dropped connection — each one fatal to the page. |
| 16 | + * Returning to the tab fires the focus handler, so the data is still fresh on arrival. |
| 17 | + */ |
10 | 18 | export function useAutoRevalidate(options: UseAutoRevalidateOptions = {}) { |
11 | 19 | const { interval = 5000, onFocus = true, disabled = false } = options; |
12 | 20 | const revalidator = useRevalidator(); |
13 | | - const revalidatorRef = useRef(revalidator); |
14 | | - // oxlint-disable-next-line react/refs -- This ref intentionally coordinates an imperative integration outside React state. |
15 | | - revalidatorRef.current = revalidator; |
16 | 21 |
|
17 | | - useEffect(() => { |
18 | | - if (!interval || interval <= 0 || disabled) return; |
19 | | - |
20 | | - const intervalId = setInterval(() => { |
21 | | - if (revalidatorRef.current.state === "loading") { |
| 22 | + useInterval({ |
| 23 | + interval, |
| 24 | + onFocus, |
| 25 | + disabled, |
| 26 | + onLoad: false, |
| 27 | + callback: () => { |
| 28 | + if (revalidator.state === "loading") { |
22 | 29 | return; |
23 | 30 | } |
24 | | - revalidatorRef.current.revalidate(); |
25 | | - }, interval); |
26 | | - |
27 | | - return () => clearInterval(intervalId); |
28 | | - }, [interval, disabled]); |
29 | | - |
30 | | - useEffect(() => { |
31 | | - if (!onFocus || disabled) return; |
32 | | - |
33 | | - const handleFocus = () => { |
34 | | - if (document.visibilityState === "visible" && revalidatorRef.current.state !== "loading") { |
35 | | - revalidatorRef.current.revalidate(); |
36 | | - } |
37 | | - }; |
38 | | - |
39 | | - // Revalidate when the page becomes visible |
40 | | - document.addEventListener("visibilitychange", handleFocus); |
41 | | - // Revalidate when the window gains focus |
42 | | - window.addEventListener("focus", handleFocus); |
43 | | - |
44 | | - return () => { |
45 | | - document.removeEventListener("visibilitychange", handleFocus); |
46 | | - window.removeEventListener("focus", handleFocus); |
47 | | - }; |
48 | | - }, [onFocus, disabled]); |
| 31 | + revalidator.revalidate(); |
| 32 | + }, |
| 33 | + }); |
49 | 34 |
|
50 | 35 | return revalidator; |
51 | 36 | } |
0 commit comments