-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathuseGetCountDownAndFeeRateStats.ts
More file actions
60 lines (51 loc) · 1.78 KB
/
useGetCountDownAndFeeRateStats.ts
File metadata and controls
60 lines (51 loc) · 1.78 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
import { useState, useEffect, useCallback } from 'react'
import { getFeeRateStatistics } from 'services/chain'
import { MEDIUM_FEE_RATE, METHOD_NOT_FOUND } from 'utils/const'
type CountdownOptions = {
seconds?: number
interval?: number
}
const useGetCountDownAndFeeRateStats = ({ seconds = 30, interval = 1000 }: CountdownOptions = {}) => {
const [countDown, setCountDown] = useState(seconds)
const [feeFatestatsData, setFeeFatestatsData] = useState<{
mean?: string
median?: string
suggestFeeRate: number
}>({ suggestFeeRate: MEDIUM_FEE_RATE })
const handleGetFeeRateStatistics = useCallback(() => {
getFeeRateStatistics()
.then(res => {
const { median } = res ?? {}
const suggested = median ? Math.max(1000, Number(median)) : MEDIUM_FEE_RATE
setFeeFatestatsData(states => ({ ...states, ...res, suggestFeeRate: suggested }))
})
.catch((err: Error & { response?: { status: number } }) => {
try {
if (err?.response?.status === 404) {
throw new Error('method not found')
}
const errMsg = JSON.parse(err.message)
if (errMsg?.code === METHOD_NOT_FOUND) {
throw new Error('method not found')
}
} catch (error) {
setFeeFatestatsData(states => ({ ...states, suggestFeeRate: MEDIUM_FEE_RATE }))
}
})
}, [])
useEffect(() => {
const countInterval = setInterval(() => {
setCountDown(count => (count <= 0 ? seconds : count - 1))
}, interval)
return () => {
clearInterval(countInterval)
}
}, [])
useEffect(() => {
if (countDown === seconds) {
handleGetFeeRateStatistics()
}
}, [countDown, seconds])
return { countDown, ...feeFatestatsData }
}
export default useGetCountDownAndFeeRateStats