-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplug.tsx
65 lines (57 loc) · 1.7 KB
/
plug.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {
plugActions,
selectPlugState,
useAppDispatch,
useAppSelector,
} from '@/store';
import { Principal } from '@dfinity/principal';
import { useCallback } from 'react';
/**
* Declare plug and it functions
* Example of a component that displays plug connection
*/
export const plug = (window as any).ic?.plug;
const requestConnect = () =>
plug?.requestConnect({
whitelist: ['3xwpq-ziaaa-aaaah-qcn4a-cai'],
});
const getPrincipal = () => plug?.getPrincipal();
const requestDisconnect = () => plug?.disconnect();
/**
* Plug Section React Component
*/
export const PlugSection = () => {
// Use states from store
const { principal, isLoading } = useAppSelector(selectPlugState);
const dispatch = useAppDispatch();
// Create a function to handle connection and app states
const handleConnect = useCallback(() => {
dispatch(plugActions.setIsLoading(true));
requestConnect()
.then(getPrincipal)
.then((response: Principal) =>
dispatch(plugActions.setPrincipal(response))
)
.finally(() => dispatch(plugActions.setIsLoading(false)));
}, [dispatch]);
// Create a function to handle disconnection and app states
const handleDisconnect = useCallback(() => {
requestDisconnect();
dispatch(plugActions.setPrincipal(undefined));
}, [dispatch]);
return (
<section>
<h1>Plug Connection</h1>
{isLoading ? (
'Loading...'
) : principal ? (
<>
{principal.toString()}
<button onClick={handleDisconnect}>Disconnect</button>
</>
) : (
<button onClick={handleConnect}>Connect</button>
)}
</section>
);
};