I added the onAccountChanged listener to my useEffect and it correctly detects Metamask account changes, but the balance does not update when I call web3Api.account.getNativeBalance. I’m trying to listen for account changes and update the displayed balance.
Before trying Moralis, this all worked perfectly with ethers.js along the following lines, in useEffect:
function addWalletListener() {
      if (window.ethereum) {
        window.ethereum.on("accountsChanged", (accounts) => {
          if (accounts.length > 0) {
            setUserAccount(accounts[0]);
            getUserBalance(accounts[0]);
            setStatus("Got the account balance");
          } else {
            setUserAccount(null);
            setUserBalance(0);
            setIsConnected(false);
            setStatus("Metamask is installed but not connected");
          }
        });
      } else {
        setUserAccount(null);
        setUserBalance(0);
        setIsMetamask(false);
        setIsConnected(false);
        setStatus("Install Metamask for more features");
      }
    }
I’m trying to do the same thing in Moralis with this:
 const Web3Api = useMoralisWeb3Api();
  const {
    Moralis,
    authenticate,
    isAuthenticated,
    isAuthenticating,
    user,
    logout,
  } = useMoralis();
const [nativeBalance, setNativeBalance] = useState();
  useEffect(() => {
    async function getNativeBalance() {
      const { balance } = await Web3Api.account.getNativeBalance({
        chain: Moralis.chainId,
        account: Moralis.account,
      });
      console.log("Just got native balance", balance);
      setNativeBalance(balance);
    }
    if (isAuthenticated) {
      getNativeBalance();
    }
    const unsubAccountChanged = Moralis.onAccountChanged((account) => {
      console.log("New Account: ", account);
      console.log("Moralis Acct: ", Moralis.account);
      getNativeBalance();
    });
    const unsubChainChanged = Moralis.onChainChanged((chain) => {
      console.log(chain);
      console.log(Moralis.chainId);
      window.location.reload();
    });
    return () => {
      unsubAccountChanged();
      unsubChainChanged();
    };
  }, [
    isAuthenticated,
    Moralis.account,
    Moralis.chainId,
    Moralis,
    Web3Api.account,
  ]);
If you check the console, the account in Moralis is changing when I change the account in Metamask, but the nativeBalance is not changing.
Any ideas what I’m doing wrong here?
 
      
    

