1
+ import { useState , useEffect } from "react" ;
2
+ import PrimaryButton from "../components/primary-button" ;
3
+
1
4
export default function Home ( ) {
2
- return < p > The start of our app!</ p >
5
+ const [ ethereum , setEthereum ] = useState ( undefined ) ;
6
+ const [ connectedAccount , setConnectedAccount ] = useState ( undefined ) ;
7
+
8
+ const handleAccounts = ( accounts ) => {
9
+ if ( accounts . length > 0 ) {
10
+ const account = accounts [ 0 ] ;
11
+ console . log ( 'We have an authorized account: ' , account ) ;
12
+ setConnectedAccount ( account ) ;
13
+ } else {
14
+ console . log ( "No authorized accounts yet" )
15
+ }
16
+ } ;
17
+
18
+ const getConnectedAccount = async ( ) => {
19
+ if ( window . ethereum ) {
20
+ setEthereum ( window . ethereum ) ;
21
+ }
22
+
23
+ if ( ethereum ) {
24
+ const accounts = await ethereum . request ( { method : 'eth_accounts' } ) ;
25
+ handleAccounts ( accounts ) ;
26
+ }
27
+ } ;
28
+ useEffect ( ( ) => getConnectedAccount ( ) , [ ] ) ;
29
+
30
+ const connectAccount = async ( ) => {
31
+ if ( ! ethereum ) {
32
+ alert ( 'MetaMask is required to connect an account' ) ;
33
+ return ;
34
+ }
35
+
36
+ const accounts = await ethereum . request ( { method : 'eth_requestAccounts' } ) ;
37
+ handleAccounts ( accounts ) ;
38
+ } ;
39
+
40
+
41
+ if ( ! ethereum ) {
42
+ return < p > Please install MetaMask to connect to this site</ p >
43
+ }
44
+
45
+ if ( ! connectedAccount ) {
46
+ return < PrimaryButton onClick = { connectAccount } > Connect MetaMask Wallet</ PrimaryButton >
47
+ }
48
+
49
+ return < p > Connected Account: { connectedAccount } </ p >
3
50
}
0 commit comments