0

I am trying to add this code to handle the change of accounts in Metamask...

ethereum
  .request({ method: 'eth_accounts' })
  .then(handleAccountsChanged)
  .catch((err: any) => {
    // Some unexpected error.
    // For backwards compatibility reasons, if no accounts are available,
    // eth_accounts will return an empty array.
    console.error(err);
  });

  if (ethereum) {
    // running on client and window + ethereum is avail
    console.log("client")
  } else {
    // you are on the server.
    // OR user does not have a broswer wallet - i.e. metamask
  }
// Note that this event is emitted on page load.
// If the array of accounts is non-empty, you're already
// connected.
ethereum.on('accountsChanged', handleAccountsChanged);

...but I am getting the following error in my TypeScript project:

TypeError: Cannot read properties of null (reading 'request')

ethereum has been defined like this, using metamask-react:

  const { status, connect, account, chainId, ethereum } = useMetaMask();

It seems that the object ethereum is not being correctly loaded.

Any thoughts?

2 Answers 2

1

although npm page says ts support but type for ethereum is any in the source code.

export declare function useConnectedMetaMask(): {
    account: string;
    chainId: string;
    status: "connected";
} & {
    connect: () => Promise<string[] | null>;
    addChain: (parameters: import("./metamask-context").AddEthereumChainParameter) => Promise<void>;
    switchChain: (chainId: string) => Promise<void>;
    ethereum: any;
};

I posted the proper type for Ethereum in this StackOverflow post.

Initially, I had the same error, the request was not sending to pop up the metamask window. It was because I was already connected to the metamask at localhost:3000 from my other apps. So I manually disconnected and set useEffect

 const { status, connect, account, chainId, ethereum } = useMetaMask();

useEffect(() => {
    ethereum?.request({ method: "eth_requestAccounts" });

  }, []);

when page was loading, I get metamask window pop-up.

0

Try:

import { ExternalProvider } from '@ethersproject/providers';

 declare global {
   interface Window {
     ethereum?: ExternalProvider
   }
 }

On your app.tsx and call ethereum object as window.ethereum. The object will be only avaiable if there's any metamask account logged so you need to verify:

if(!window.ethereum){
console.log('no ethereum wallet connected')
}

Your Answer

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

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