-
-
Save leonnardovv/3cff383bf3a3d3a582b91e581fa4f112 to your computer and use it in GitHub Desktop.
Example of connecting to an Ethereum wallet using React & Web3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react' | |
import Web3 from 'web3' | |
const [account, setAccount] = useState(null) | |
let [web3, setWeb3] = useState(null) | |
useEffect(() => { | |
checkAccount() | |
}, []) | |
// invoke to connect to wallet account | |
async function activate() { | |
if (window.ethereum) { | |
try { | |
await window.ethereum.request({ method: 'eth_requestAccounts' }); | |
checkAccount() | |
} catch (err) { | |
console.log('user did not add account...', err) | |
} | |
} | |
} | |
// invoke to check if account is already connected | |
async function checkAccount() { | |
let web3 = new Web3(window.ethereum) | |
setWeb3(web3) | |
const accounts = await web3.eth.getAccounts() | |
setAccount(accounts[0]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment