Skip to content

Instantly share code, notes, and snippets.

@leonnardovv
Forked from dabit3/react-web3-example.js
Created December 18, 2021 22:49
Show Gist options
  • Save leonnardovv/3cff383bf3a3d3a582b91e581fa4f112 to your computer and use it in GitHub Desktop.
Save leonnardovv/3cff383bf3a3d3a582b91e581fa4f112 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