Skip to content

Commit fb59079

Browse files
committed
Add custom hook for auto revalidation based on an interval and/or focus change
1 parent 55b8936 commit fb59079

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { useRevalidator } from "@remix-run/react";
2+
import { useEffect } from "react";
3+
4+
type UseAutoRevalidateOptions = {
5+
interval?: number; // in milliseconds
6+
onFocus?: boolean;
7+
};
8+
9+
export function useAutoRevalidate(options: UseAutoRevalidateOptions = {}) {
10+
const { interval = 5000, onFocus = true } = options;
11+
const revalidator = useRevalidator();
12+
13+
useEffect(() => {
14+
if (!interval || interval <= 0) return;
15+
16+
const intervalId = setInterval(() => {
17+
if (revalidator.state === "loading") {
18+
return;
19+
}
20+
revalidator.revalidate();
21+
}, interval);
22+
23+
return () => clearInterval(intervalId);
24+
}, [interval]);
25+
26+
useEffect(() => {
27+
if (!onFocus) return;
28+
29+
const handleFocus = () => {
30+
if (document.visibilityState === "visible" && revalidator.state !== "loading") {
31+
revalidator.revalidate();
32+
}
33+
};
34+
35+
// Revalidate when the page becomes visible
36+
document.addEventListener("visibilitychange", handleFocus);
37+
// Revalidate when the window gains focus
38+
window.addEventListener("focus", handleFocus);
39+
40+
return () => {
41+
document.removeEventListener("visibilitychange", handleFocus);
42+
window.removeEventListener("focus", handleFocus);
43+
};
44+
}, [onFocus]);
45+
46+
return revalidator;
47+
}

0 commit comments

Comments
 (0)