1
- import { getBalance } from '@helpers/getBalance'
1
+ import { BalanceData , getBalance , watchBalance } from '@helpers/getBalance'
2
2
import { AccountId } from '@polkadot/types/interfaces'
3
3
import { BN } from '@polkadot/util'
4
4
import { useInkathon } from '@provider'
@@ -7,39 +7,45 @@ import { useEffect, useState } from 'react'
7
7
/**
8
8
* Hook that returns the native token balance of the given `address`.
9
9
*/
10
- export const useBalance = ( address ?: string | AccountId ) => {
10
+ export const useBalance = ( address ?: string | AccountId , watch ?: boolean ) => {
11
11
const { api } = useInkathon ( )
12
12
const [ freeBalance , setFreeBalance ] = useState < BN > ( )
13
13
const [ reservedBalance , setReservedBalance ] = useState < BN > ( )
14
14
const [ balance , setBalance ] = useState < BN > ( )
15
15
const [ balanceFormatted , setBalanceFormatted ] = useState < string > ( )
16
16
const [ tokenSymbol , setTokenSymbol ] = useState < string > ( )
17
17
const [ tokenDecimals , setTokenDecimals ] = useState < number > ( )
18
+ const [ unsubscribes , setUnsubscribes ] = useState < ( VoidFunction | null ) [ ] > ( [ ] )
18
19
19
20
useEffect ( ( ) => {
20
- ; ( async ( ) => {
21
- if ( ! api ) {
22
- setFreeBalance ( undefined )
23
- setReservedBalance ( undefined )
24
- setBalance ( undefined )
25
- setBalanceFormatted ( undefined )
26
- setTokenSymbol ( undefined )
27
- setTokenDecimals ( undefined )
28
- return
29
- }
30
-
31
- const result = await getBalance ( api , address )
32
-
33
- setFreeBalance ( result . freeBalance )
34
- setReservedBalance ( result . reservedBalance )
35
- setBalance ( result . balance )
21
+ const updateBalanceData = ( data : BalanceData ) => {
22
+ setFreeBalance ( data . freeBalance )
23
+ setReservedBalance ( data . reservedBalance )
24
+ setBalance ( data . balance )
36
25
setBalanceFormatted (
37
- result . balanceFormatted &&
38
- `${ result . balanceFormatted } ${ result . tokenSymbol } ` ,
26
+ data . balanceFormatted && `${ data . balanceFormatted } ${ data . tokenSymbol } ` ,
39
27
)
40
- setTokenSymbol ( result . tokenSymbol )
41
- setTokenDecimals ( result . tokenDecimals )
42
- } ) ( )
28
+ setTokenSymbol ( data . tokenSymbol )
29
+ setTokenDecimals ( data . tokenDecimals )
30
+ }
31
+
32
+ if ( ! api ) {
33
+ updateBalanceData ( { } as BalanceData )
34
+ return
35
+ }
36
+
37
+ if ( watch ) {
38
+ watchBalance ( api , address , updateBalanceData ) . then ( ( unsubscribe ) => {
39
+ setUnsubscribes ( ( prev ) => [ ...prev , unsubscribe ] )
40
+ } )
41
+ } else {
42
+ getBalance ( api , address ) . then ( updateBalanceData )
43
+ }
44
+
45
+ return ( ) => {
46
+ unsubscribes . forEach ( ( unsubscribe ) => unsubscribe ?.( ) )
47
+ setUnsubscribes ( ( ) => [ ] )
48
+ }
43
49
} , [ api , address ] )
44
50
45
51
return {
0 commit comments