Cannot read properties of null (reading 'network'), React

Implementing the Moralis Providers and trying to have a user connect their wallet and mint an NFT.

This is what I have implemented

import { useMoralis } from "react-moralis";

export default function ConnectWallet() {
  const {
    authenticate,
    isAuthenticated,
    logout,
    user,
    web3,
    enableWeb3,
    isWeb3Enabled,
    web3EnableError,
  } = useMoralis();

  const networks = {
    1: "Ethereum Mainnet",
    4: "Rinkeby Testnet",
    97: "Binance Smart Chain Testnet",
    80001: "Polygon Mumbai Testnet",
  };

  async function authMetamask() {
    const localChainId = web3.network.chainId;
    const checkMetaMask = web3.provider.isMetaMask;

    if (localChainId == 1 && checkMetaMask) {
      await authenticate({ provider: "metamask", signingMessage: "ThePeepsProject Auth" });
    } else {
      handleError();
    }
  }

  async function login() {
    if (!isWeb3Enabled) {
      web3Enabler();
    } else {
      await authMetamask();
    }
  }

  const web3Enabler = async () => {
    await enableWeb3({
      onSuccess: () => {
        const localChainId = web3.network.chainId;
        const checkMetaMask = web3.provider.isMetaMask;

        console.log("Web3 Provider: ", web3.connection.url);
        console.log("Network Name: ", networks[localChainId]);

        if (localChainId == 1 && checkMetaMask) {
          authMetamask();
        } else if (!checkMetaMask) {
          console.log("checkMetaMask: ", checkMetaMask);
          console.log("Please install MetaMask");
        } else if (localChainId != 1) {
          console.log("Must use Eth Mainnet");
        } else {
          console.log("Something went wrong");
        }
      },
      onError: (error) => {
        console.log("Web3 Enable Error: ", error.message);
        if (error.message == "Non ethereum enabled browser") {
          alert("Metamask is not installed.\nPlease install it and setup a wallet to continue");
        }
      },
    });
  };

  function handleError(message) {
    const localChainId = web3.network.chainId;
    const checkMetaMask = web3.provider.isMetaMask;

    if (!checkMetaMask) {
      alert("Metamask is not installed.\nPlease install it and setup a wallet to continue");
    } else if (localChainId != 1 && localChainId != 4) {
      alert("Please ensure you are on the Etherium Mainnet to mint");
    }
  }

  return (
    <div>
      <main>
        <div>
          {isAuthenticated ? (
            <button onClick={logout}>
                Logout ({user.get("ethAddress").slice(0, 6)}...{user.get("ethAddress").slice(37, 41)})
            </button>
          ) : (
            <button type="button" onClick={() => login()}>
                Connect with MetaMask
            </button>
          )}
        </div>
      </main>
    </div>
  );
}

Everytime a wallet gets connected, it shows an error in the console:
Web3 Enable Error: Cannot read properties of null (reading 'network')

Coming from the lines:

onError: (error) => {
        console.log("Web3 Enable Error: ", error.message);

The function is doing it’s job of catching an error, but what is this error and how can I fix it?

How can I check if the user has metamask installed and ensure that they are on the Mainnet before they can run the function?

@TJ-TMT from where did you get web3.network.chainId?

Was in the docs, Not sure exactly where I found it.

I believe from something similar to this:

You can get chainId in react this way const { chain, chainId } = useChain(); and get the list of supported network chainId here https://docs.moralis.io/moralis-dapp/web3-api/supported-chains.

The chain here is the the object of the user current network

If we use const { chain, chainId } = useChain(), the values of these variables become null when we reload or refresh the page.

when do you read them?

do you use useEffect?

I did not use useEffect.
The following snippet is the way I used.

import React from "react";
import { useChain } from "react-moralis";

const App = () => {
    const { chain, chainId } = useChain();
    console.log("chain: ", chain);
    console.log("chainId: ", chainId);

    return(<h1>Test useChain</h1>);
};

export default App;

that may not always work, you may have to use useEffect and to check dependencies in useEffect

1 Like