Skip to content
This repository was archived by the owner on Dec 19, 2024. It is now read-only.

Commit b0938a6

Browse files
committed
ConnectToWalletButton component
npm install web3 src/components/ConnectToWalletButton.js adding ConnectToWalletButton to Header Updating ConnectToWalletButton - no web3 yet using window.ethereum.isMetaMask reverting web3 add Updating ConnectToWalletButton based on React best practices more guards against missing window.ethereum tidying up even more with conditional chaining reverting changes to Header finishing touches on ConnectWalletButton
1 parent 6e6704e commit b0938a6

File tree

2 files changed

+95
-36
lines changed

2 files changed

+95
-36
lines changed

package-lock.json

Lines changed: 51 additions & 36 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import React, { useState, useEffect } from 'react'
2+
import { Button } from 'evergreen-ui'
3+
4+
function truncateAddress (address) {
5+
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`
6+
}
7+
8+
function isMetaMask () { return window.ethereum?.isMetaMask }
9+
10+
function ConnectToWalletButton (props) {
11+
const [address, setAddress] = useState(window.ethereum?.selectedAddress)
12+
const [loading, setLoading] = useState(false)
13+
14+
useEffect(() => {
15+
const firstAddress = (addr) => setAddress(addr[0])
16+
window.ethereum?.on('accountsChanged', firstAddress)
17+
18+
return function cleanup () {
19+
window.ethereum?.removeListener('accountsChanged', firstAddress)
20+
}
21+
}, [])
22+
23+
async function connectWallet (event) {
24+
setLoading(true)
25+
26+
window.ethereum?.request({ method: 'eth_requestAccounts' })
27+
.catch(console.error)
28+
.finally(() => setLoading(false))
29+
}
30+
31+
if (!isMetaMask()) return null
32+
return (
33+
<Button
34+
intent={address ? 'success' : 'none'}
35+
style={props.style}
36+
isLoading={loading}
37+
onClick={connectWallet}
38+
>
39+
{address ? truncateAddress(address) : 'Connect wallet'}
40+
</Button>
41+
)
42+
}
43+
44+
export default ConnectToWalletButton

0 commit comments

Comments
 (0)