Connecting to Ethereum: RPC

Get current block number

Ref : https://docs.ethers.io/v5/getting-started/#getting-started--connecting-rpc

alchmey Provider

Create an acount in alchemy.com and get the url with APIKey

const url = ("xxx") // change with your alchemi url
const provider = new ethers.providers.JsonRpcProvider(url);

getBlockNumber()

const response = await provider.getBlockNumber()

Full Code

import { ethers } from "ethers";
import React, { useState, useEffect } from 'react'

const App = () => {
const [block, setBlock] = useState("")

const getBlock = async () => {
        const url = ("xxx") // change with your alchemi url
        const provider = new ethers.providers.JsonRpcProvider(url);
        try {
          const response = await provider.getBlockNumber()
          setBlock(response)
          
        } catch (error) {
          console.log(error, 'ini error block')
        }
      }
    
    useEffect(() => {
        getBlock()
        return () => {
        setBlock("")
        }
      }, [])

return (
<Box>
  {block}
 </Box> 
)
}

export default AppBarTop

Last updated

Was this helpful?