We need a way for our user’s MetaMask wallets to connect to our dApp. We can accomplish this with the ethereum
object that MetaMask injects into the browser’s window
.
When the user connects we’ll save their wallet address as state using the useState
hook.
Instructor: [0:00] For users to connect their metamask extension to our application, we need to wire up this connect button. Let's go to VS Code. In the connect component, let's add a new function called connectWallet. Const connectWallet equals async.
[0:16] In here, we're going to check for the Ethereum object on our window, which gets injected by the metamask extension. We'll say const Ethereum equals window. If not Ethereum, then we'll just return early. Next, we'll add a try block, try catch.
[0:41] In the try block, we're going to make a request to the metamask extension to give us access to the accounts it manages. We'll say const accounts equals await Ethereum.request. This takes an object, and we'll add the method field with a value of ETH request accounts.
[1:06] Well, we could store the account information in this component using useState. We want to elevate this to our parent component app. Let's open it. Here, we'll import useState from React. Import useState from React. We'll come down below and add a new state value.
[1:28] Const address, setAddress equals useState. Right now, we'll set that to null. We'll add a new prop to our connect component, call it onConnect. We'll make it a function. The connect component is going to return to us the wallet address. We'll say, address here.
[1:52] Then inside the function, we'll call the setter function, setAddress, and set it to address. We'll also pass the value of address as a prop to connect, address equals address. We'll also log out the value of address here, console.log address, address.
[2:16] Back in connect, we now need to update our props here. We're getting an address and an onConnect function. We want to update our connectWallet function as well. Accounts is a list of addresses managed by the metamask extension.
[2:31] We'll just take the first one by default, onConnect, and we'll pass that accounts zero. Lastly, we just need to wire up the connectWallet function to our button, our connect button here. We'll say, onClick equals connectWallet.
[2:50] If we come to the browser and open our console, you'll see the address is null. If we click connect, it'll ask us if we want to connect our metamask wallet. We'll say, yes, connect. Now we have a wallet address here in our console.
[3:05] To review, we connected our metamask wallet to our React app using the connectWallet function, and the Ethereum object on the window.