-
Notifications
You must be signed in to change notification settings - Fork 0
/
useSimpleAutoRefreshQuery.ts
173 lines (148 loc) · 5.56 KB
/
useSimpleAutoRefreshQuery.ts
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { useContext, useRef, useEffect, useState, useCallback } from 'react'
import { defaults, noop } from 'lodash'
import moment from 'moment-timezone'
import {
useSimpleQuery,
UseSimpleQueryProps,
UseSimpleQueryReturn,
} from './useSimpleQuery'
import { ItiReactCoreContext } from '../../ItiReactCoreContext'
declare function setTimeout(func: () => void, delay: number): number
declare function clearTimeout(timer: number | undefined): void
/* connectionErrorThreshold was added because single API calls can fail in certain
* cases when the user actually does have an internet connection. The case that we've
* observed is when the computer has been asleep. The AutoRefreshUpdater will typically
* query immediately after the computer resumes, and the request will fail because
* network IO hasn't been re-enabled yet.
*/
export interface AutoRefreshOptions {
refreshInterval?: moment.Duration
enableAutoRefresh?: boolean
onRefreshingChange?: (refreshing: boolean) => void
onConnectionError(): void
onOtherError?(e: unknown): void
}
export type UseSimpleAutoRefreshQueryProps<TQueryParams, TResult> = Pick<
UseSimpleQueryProps<TQueryParams, TResult>,
| 'queryParams'
| 'query'
| 'shouldQueryImmediately'
| 'onResultReceived'
| 'onLoadingChange'
| 'debounceDelay'
> &
AutoRefreshOptions
/**
* @deprecated
*
* Performs a query on mount and repeats the query according to `refreshInterval`.
*
* Example:
* ```
* const { doQuery, doQueryAsync } = useParameterlessAutoRefreshQuery<WorkDocId, WorkDocDto>({
* queryParams: workDocId,
* query: (id) => api.workDoc.get({ id }),
* shouldQueryImmediately: (prev, cur) => true,
* onResultReceived: (workDoc) => {
* setWorkDoc(workDoc)
* dispatch(setShowBackendUnreachableAlert(false))
* },
* refreshInterval: dayjs.duration(1, 'minute'),
* onConnectionError: () => dispatch(setShowBackendUnreachableAlert(true))
* })
* ```
*
* @typeParam TQueryParams the parameters of the query
* @typeParam TResult the type returned by the query
*/
export function useSimpleAutoRefreshQuery<TQueryParams, TResult>(
props: UseSimpleAutoRefreshQueryProps<TQueryParams, TResult>
): UseSimpleQueryReturn {
const itiReactCoreContext = useContext(ItiReactCoreContext)
const { defaultRefreshInterval, isConnectionError, connectionErrorThreshold } =
itiReactCoreContext.useSimpleAutoRefreshQuery
const {
refreshInterval,
enableAutoRefresh,
onRefreshingChange,
onConnectionError,
onOtherError,
} = defaults(
{ ...props },
{
onRefreshingChange: noop,
enableAutoRefresh: true,
onOtherError: itiReactCoreContext.onError,
refreshInterval: defaultRefreshInterval,
startAutoRefreshOnMount: true,
}
)
const autoRefreshTimerRef = useRef<number>()
const [shouldRestartTimer, setShouldRestartTimer] = useState(false)
// So that onConnectionError is called immediately if the initial query fails
const consecutiveConnectionErrorCountRef = useRef(connectionErrorThreshold - 1)
const onError = useCallback(
(e: unknown): void => {
if (isConnectionError(e)) {
consecutiveConnectionErrorCountRef.current += 1
if (
consecutiveConnectionErrorCountRef.current >= connectionErrorThreshold
) {
onConnectionError()
}
} else {
onOtherError(e)
}
},
[isConnectionError, connectionErrorThreshold, onConnectionError, onOtherError]
)
const onQueryStarted = useCallback(() => {
if (enableAutoRefresh) setShouldRestartTimer(true)
}, [enableAutoRefresh])
const { doQuery, doQueryAsync } = useSimpleQuery({
queryParams: props.queryParams,
query: props.query,
shouldQueryImmediately: props.shouldQueryImmediately,
onResultReceived: props.onResultReceived,
onLoadingChange: props.onLoadingChange,
debounceDelay: props.debounceDelay,
onQueryStarted,
onError,
})
const firstTimeRef = useRef(true)
// Immediately perform the query if enableAutoRefresh goes from false to true
useEffect(() => {
if (enableAutoRefresh && !firstTimeRef.current) doQuery()
firstTimeRef.current = false
}, [enableAutoRefresh, doQuery])
const refresh = useCallback(async (): Promise<void> => {
onRefreshingChange(true)
try {
await doQueryAsync({ changeLoading: false })
consecutiveConnectionErrorCountRef.current = 0
// See note in useParameterizedQuery about onLoadingChange for why
// onRefreshingChange(false) should NOT be called in a finally block
onRefreshingChange(false)
} catch (e) {
onError(e)
}
}, [doQueryAsync, onRefreshingChange, onError])
const refreshIntervalMilliseconds = refreshInterval.asMilliseconds()
useEffect(() => {
if (shouldRestartTimer) {
setShouldRestartTimer(false)
clearTimeout(autoRefreshTimerRef.current)
autoRefreshTimerRef.current = setTimeout(() => {
void refresh()
}, refreshIntervalMilliseconds)
}
}, [shouldRestartTimer, refresh, refreshIntervalMilliseconds])
// Final cleanup
useEffect(
() => (): void => {
clearTimeout(autoRefreshTimerRef.current)
},
[]
)
return { doQuery, doQueryAsync }
}