0

I want to get network chainId from web3Provider. This is my code.

const isBrowser = typeof window !== "undefined";
const web3provider = isBrowser ? new ethers.providers.Web3Provider(window.ethereum) : null;

const currentChainId = web3provider.network.chainId;

But I get this error. Cannot read properties of undefined (reading 'chainId')

Please tell me how can I access network attribute in web3provider. (Documentation says it's not safe way to access web3provider._network)

1 Answer 1

0

Try to await the network with getNetwork() (docs here), and then access the id with network.chainId (docs here).

Here is some example code:

const isBrowser = typeof window !== "undefined";
const web3provider = isBrowser ? new ethers.providers.Web3Provider(window.ethereum) : null;

// await network and return chainId
async function getCurrentChainId() {
  if (!web3provider) return null;
  const network = await web3provider.getNetwork();
  return network.chainId;
}

// await async function
const currentChainId = await getCurrentChainId();

// log the chainId
console.log(currentChainId);
2
  • Thank you. It worked. Mar 7, 2023 at 22:43
  • awesome. feel free to accept the answer so that it no longer appears in the open questions.
    – timsntech
    Mar 7, 2023 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.