Event listener when the user changes chains?

I know there is Moralis.Web3.onAccountsChanged but is there an equivalent when they change their chain? For example I am using the same account number, but switch from Ethereum Mainnet to Ropsten. Or Ethereum to Binance.

Thanks!

Hey @tsuri

Yes, there is onChainChanged. Take a look at:
https://docs.moralis.io/moralis-server/web3/web3-1#events

Happy BUIDLing!

1 Like

Hi @Yomoo How can I get the current chain without going thru onChainChanged? And in general is there a link to docs that shows stuff like all the functions in Moralis.Web3, the structure of Moralis.User.Current() when I search around all I see is the REST API docs. Thanks!

Hi @tsuri

You can get the current chain using:

const web3 = await Moralis.Web3.enable();
const chainId = web3.currentProvider.chainId;
console.log(chainId);

Our docs are seperated on blocks and they are separated on the topics:

image

Moralis has own functions like Moralis.Web3.getAllERC20() but it also supports Web3 functions.
Take a look at: https://docs.moralis.io/moralis-server/web3/web3-1#in-browser

Happy BUIDLing

1 Like

Hello, is there a way to use the onChainChanged function in react?

Hi @benlive

  const { Moralis } = useMoralis();

  Moralis.onChainChanged(async function (chain) {
    console.log(chain);
  });
3 Likes

@Yomoo thank you. This solution works, but I noticed that when I change the chain this function is called not once but 16 times. Is this a problem with moralis function or am I doing something wrong?

image

Thanks

Hey @benlive

I guess you have this problem because of rerenering of the component. I suggest you to wrap a listener in useEffect hook

1 Like