-
Notifications
You must be signed in to change notification settings - Fork 1
/
wallet-context.tsx
50 lines (43 loc) · 1.53 KB
/
wallet-context.tsx
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
import React, { createContext, useContext, useEffect, useState, useRef } from 'react';
import { WalletService, WalletState } from '../services/wallet-service';
import { MessageService, GrpcService } from '../services';
type State = {
walletService: WalletService;
walletState: WalletState;
messageService: MessageService;
grpcService: GrpcService;
};
const StateContext = createContext<State | undefined>(undefined);
const walletService = new WalletService();
const messageService = new MessageService();
const WalletContextProvider = ({
children,
grpcServiceAddress,
walletUrl,
}: {
children: React.ReactElement;
grpcServiceAddress?: string;
walletUrl?: string;
}) => {
const [walletState, setWalletState] = useState<WalletState>({ ...walletService.state });
const grpcServiceRef = useRef(grpcServiceAddress ? new GrpcService(grpcServiceAddress) : undefined);
useEffect(() => {
walletService.setStateUpdater(setWalletState);
if (walletUrl) walletService.setWalletUrl(walletUrl);
return () => walletService.removeAllEventListeners();
// eslint-disable-next-line
}, []);
return (
<StateContext.Provider value={{ walletService, walletState, messageService, grpcService: grpcServiceRef.current as GrpcService }}>
{children}
</StateContext.Provider>
);
};
const useWallet = () => {
const context = useContext(StateContext);
if (context === undefined) {
throw new Error('useWallet must be used within a WalletContextProvider');
}
return context;
};
export { WalletContextProvider, useWallet };