-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuse-swap-canister-balances.ts
59 lines (54 loc) · 1.86 KB
/
use-swap-canister-balances.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
import {
balanceActions,
selectBalanceState,
useAppDispatch,
useAppSelector,
} from '@/store';
import { Token } from '@psychedelic/sonic-js';
import { useCallback } from 'react';
import { useSwapCanisterController } from '.';
/**
* Example of creating a custom hook for balances usage
*/
export const useSwapCanisterBalances = (): {
balanceList?: Token.BalanceList;
isLoading: boolean;
updateBalanceList: (principalId?: string) => void;
balanceOf: string | undefined;
} => {
// Use the SwapCanisterController hook
const controller = useSwapCanisterController();
// Use states from store
const { balanceList, isLoading, balanceOf } =
useAppSelector(selectBalanceState);
const dispatch = useAppDispatch();
/**
* Creating a function to get balances list and add it on redux store
*/
const updateBalanceList = useCallback(
(principalId?: string) => {
if (controller) {
// If no principalId is provided, let's get the agent principal to store
if (!principalId) {
controller
.getAgentPrincipal()
.then((agentPrincipal) =>
dispatch(balanceActions.setBalanceOf(agentPrincipal.toString()))
)
.catch((error) => alert(error));
} else {
dispatch(balanceActions.setBalanceOf(principalId));
}
// Get balances from controller and manage app loading states
dispatch(balanceActions.setIsLoading(true));
controller
.getTokenBalances(principalId)
.then((response) => dispatch(balanceActions.setBalanceList(response)))
.catch((error) => alert(error))
.finally(() => dispatch(balanceActions.setIsLoading(false)));
}
},
[controller, dispatch]
);
return { balanceList, isLoading, updateBalanceList, balanceOf };
};