File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments