forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePolling.ts
More file actions
136 lines (116 loc) · 3.44 KB
/
Copy pathusePolling.ts
File metadata and controls
136 lines (116 loc) · 3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import { useEffect, useRef, useCallback, useState } from 'react';
export interface PollingOptions<T> {
fetchFn: () => Promise<T>;
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
interval?: number;
enabled?: boolean;
maxRetries?: number;
retryDelay?: number;
}
export interface PollingState {
isLoading: boolean;
isRefreshing: boolean;
error: Error | null;
lastUpdated: Date | null;
}
export function usePolling<T>({
fetchFn,
onSuccess,
onError,
interval = 15000, // 15 seconds default
enabled = true,
maxRetries = 3,
retryDelay = 1000, // 1 second initial backoff
}: PollingOptions<T>): PollingState {
const [state, setState] = useState<PollingState>({
isLoading: true,
isRefreshing: false,
error: null,
lastUpdated: null,
});
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const isMountedRef = useRef(true);
const retryCountRef = useRef(0);
const isTabVisibleRef = useRef(true);
const executeFetch = useCallback(async (isInitial = false) => {
if (!isMountedRef.current) return;
setState(prev => ({
...prev,
isLoading: isInitial,
isRefreshing: !isInitial && isTabVisibleRef.current,
error: null,
}));
try {
const data = await fetchFn();
if (isMountedRef.current) {
onSuccess?.(data);
setState(prev => ({
...prev,
isLoading: false,
isRefreshing: false,
error: null,
lastUpdated: new Date(),
}));
retryCountRef.current = 0; // Reset retry count on success
}
} catch (error) {
console.error('Polling fetch failed:', error);
if (isMountedRef.current) {
const shouldRetry = retryCountRef.current < maxRetries;
if (shouldRetry) {
retryCountRef.current++;
const backoffDelay = retryDelay * Math.pow(2, retryCountRef.current - 1);
timeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
executeFetch(false);
}
}, backoffDelay);
} else {
onError?.(error as Error);
setState(prev => ({
...prev,
isLoading: false,
isRefreshing: false,
error: error as Error,
}));
}
}
}
}, [fetchFn, onSuccess, onError, maxRetries, retryDelay]);
// Handle visibility change
useEffect(() => {
const handleVisibilityChange = () => {
isTabVisibleRef.current = document.visibilityState === 'visible';
if (isTabVisibleRef.current && enabled) {
// Resume polling - fetch immediately
executeFetch(false);
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [enabled, executeFetch]);
// Main polling effect
useEffect(() => {
isMountedRef.current = true;
if (!enabled) return;
// Initial fetch
executeFetch(true);
// Set up interval
const intervalId = setInterval(() => {
if (isTabVisibleRef.current && isMountedRef.current) {
executeFetch(false);
}
}, interval);
return () => {
isMountedRef.current = false;
clearInterval(intervalId);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [enabled, interval, executeFetch]);
return state;
}