Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active March 22, 2022 01:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dabit3/ba2685a379236d933ba85c30d00ec50c to your computer and use it in GitHub Desktop.
Save dabit3/ba2685a379236d933ba85c30d00ec50c to your computer and use it in GitHub Desktop.
Example of connecting to an Ethereum wallet using React & Web3
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