[SOLVED]How to utilize the onChainChanged and onAccountChanged?

can I know what should I do to utilize the function of onChainChange

 const xx = Moralis.onChainChanged()

I want the NativeBalance show correct value, corresponding to the MetaMask account change.

I have tried below method.

But when account change, the callback function did not trigger.

And I got below warning.

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 accountChanged listeners added. Use emitter.setMaxListeners() to increase limit

just pass the account and user, from parent component to child component, and place the account into the useEffect, dependencies.

So for the last code/warning, a listener will be set up every time one of Web3API.account, user, Web3API changes and triggers that useEffect.

Setting it up once in a useEffect with no dependencies [] should work.

You can also move fetchNativeBalance outside of the useEffect. Before setting setEthBalance, can you also log result to make sure getNativeBalance working.

yes, have changed as below, but cannot work.

import Moralis from "moralis";
import { useEffect, useState, useCallback } from "react";
import { Text } from "@chakra-ui/react";
import { useMoralisWeb3Api } from "react-moralis";
import CustomContainer from "./CustomContainer"

export default function Balance({ user }) {
  const Web3API = useMoralisWeb3Api()
  const [ethBalance, setEthBalance] = useState()

  // 1. Native Balance
  const fetchNativeBalance = useCallback(async () => {
    const chainId = Moralis.getChainId()
    const result = await Web3API.account.getNativeBalance({
      chain: chainId,
      address: user.get("ethAddress")
    console.log("ethBalance:", result)
    if (result && result.balance) {
  }, [Web3API.account, user])

  useEffect(() => {
  }, [Web3API.account, user, Web3API, fetchNativeBalance])

  return (
      <Text mb="6" fontSize={"xl"} fontWeight="bold">My NativeBalance</Text>
      {ethBalance && <Text>💲&nbsp;  {ethBalance} <b>ETH</b></Text>}

My object of user, is passed from parent component.
Should I catch the account change event ins parent component?

How to pass new user object to child component?

1 Like