1
1
import debounce from 'lodash/debounce' ;
2
2
import throttle from 'lodash/throttle' ;
3
- import { nextTick , Ref , ref } from 'vue' ;
3
+ import { computed , nextTick , Ref , ref } from 'vue' ;
4
4
import { Config } from './config' ;
5
5
import { Queries } from './useAsyncQuery' ;
6
6
import {
@@ -78,7 +78,7 @@ const createQuery = <R, P extends unknown[]>(
78
78
onError,
79
79
} = config ;
80
80
81
- let retriedCount = 0 ;
81
+ const retriedCount = ref ( 0 ) ;
82
82
const loading = ref ( initialState ?. loading ?? false ) ;
83
83
const data = ref ( initialState ?. data ?? initialData ) as Ref < R > ;
84
84
const error = ref ( initialState ?. error ) ;
@@ -96,7 +96,7 @@ const createQuery = <R, P extends unknown[]>(
96
96
97
97
// reset retried count
98
98
const resetRetriedCount = ( ) => {
99
- retriedCount = 0 ;
99
+ retriedCount . value = 0 ;
100
100
} ;
101
101
102
102
const count = ref ( 0 ) ;
@@ -154,15 +154,29 @@ const createQuery = <R, P extends unknown[]>(
154
154
return ( ) => timerId && clearTimeout ( timerId ) ;
155
155
} ;
156
156
157
+ const actualErrorRetryInterval = computed ( ( ) => {
158
+ if ( errorRetryInterval ) return errorRetryInterval ;
159
+ const baseTime = 1000 ;
160
+ const minCoefficient = 1 ;
161
+ const maxCoefficient = 9 ;
162
+ // When retrying for the first time, in order to avoid the coefficient being 0
163
+ // so replace 0 with 2, the coefficient range will become 1 - 2
164
+ const coefficient = Math . floor (
165
+ Math . random ( ) * 2 ** Math . min ( retriedCount . value , maxCoefficient ) +
166
+ minCoefficient ,
167
+ ) ;
168
+ return baseTime * coefficient ;
169
+ } ) ;
170
+
157
171
const errorRetryHooks = ( retryFunc : ( ) => void ) => {
158
172
let timerId : number ;
159
173
const isInfiniteRetry = errorRetryCount === - 1 ;
160
- const hasRetryCount = retriedCount < errorRetryCount ;
174
+ const hasRetryCount = retriedCount . value < errorRetryCount ;
161
175
162
176
// if errorRetryCount is -1, it will retry the request until it success
163
177
if ( error . value && ( isInfiniteRetry || hasRetryCount ) ) {
164
- if ( ! isInfiniteRetry ) retriedCount += 1 ;
165
- timerId = setTimeout ( retryFunc , errorRetryInterval ) ;
178
+ if ( ! isInfiniteRetry ) retriedCount . value += 1 ;
179
+ timerId = setTimeout ( retryFunc , actualErrorRetryInterval . value ) ;
166
180
}
167
181
return ( ) => timerId && clearTimeout ( timerId ) ;
168
182
} ;
0 commit comments