What type should I use for tokenBalance?

Language : typescript Version 4.1.3
Framework: next 12.1.5
Moralis : 1.5.10

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

type MyProps = {
  account: string;
};
type ChainType =
  | "eth"
  | "0x1"
  | "ropsten"
  | "0x3"
  | "rinkeby"
  | "0x4"
  | "goerli"
  | "0x5"
  | "kovan"
  | "0x2a"
  | "polygon"
  | "0x89"
  | "mumbai"
  | "0x13881"
  | "bsc"
  | "0x38"
  | "bsc testnet"
  | "0x61"
  | "avalanche"
  | "0xa86a"
  | "avalanche testnet"
  | "0xa869"
  | "fantom"
  | "0xfa"
  | undefined;
function Balance({ account }: MyProps) {
  const Web3API = useMoralisWeb3Api();
  const chainId = Moralis.getChainId() as ChainType;

  const [ethBalance, setEthBalance] = useState<string | undefined>();
  const [tokBalance, setTokBalance] = useState<string | undefined>();

  // 1. Native Balance
  const fetchNativeBalance = useCallback(async () => {
    const nativeBala = await Web3API.account.getNativeBalance({
      chain: chainId,
      address: account,
    });
    if (nativeBala && nativeBala.balance) {
      setEthBalance(Moralis.Units.FromWei(nativeBala.balance));
    }
  }, [Web3API.account, account, chainId]);

  // 2. ERC20 Balance
  const fetchTokenBalances = useCallback(async () => {
    const tokenBalances = await Web3API.account.getTokenBalances({
      chain: chainId,
      address: account,
    });
    console.log("token balances", tokenBalances);
    if (tokenBalances) {
      setTokBalance(tokenBalances);
    }
  }, [Web3API.account, account, chainId]);

The results as you defined tokenBalances have the type of Array of objects
{ token_address...; name: ...; etc... }[]. You are trying to assign this results to a type of string | undefined

1 Like

Yes, I have fixed by below action:

image

image