Last active
March 22, 2022 01:48
-
-
Save dabit3/ba2685a379236d933ba85c30d00ec50c 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