Replace it with this code.
I used fetch
from useEvmNativeBalance
to get the balance of the address.
When the component inistally renders the value of addy is undefined
so we cant directly use useEvmNativeBalance
directly to fetch the balance.
And you also need to assign the value of addy
to address
param, to read and pass the value correctly to API.
Please check with this code and let me know if you have any questions.
import { useEvmNativeBalance } from "@moralisweb3/next";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { useState, useEffect } from "react";
import { useAccount, useConnect, useSignMessage, useDisconnect } from "wagmi";
import { useAuthRequestChallengeEvm } from "@moralisweb3/next";
function HomePage() {
const { connectAsync } = useConnect();
const { disconnectAsync } = useDisconnect();
const { isConnected } = useAccount();
const { signMessageAsync } = useSignMessage();
const { requestChallengeAsync } = useAuthRequestChallengeEvm();
const [addy, setAddy] = useState();
const handleAuth = async () => {
if (isConnected) {
await disconnectAsync();
}
const { account, chain } = await connectAsync({
connector: new MetaMaskConnector(),
});
const { message } = await requestChallengeAsync({
address: account,
chainId: chain.id,
});
const signature = await signMessageAsync({ message });
setAddy(account);
console.log(signature);
};
const { data: nativeBalance, error, fetch } = useEvmNativeBalance();
// const {data: allBalance } = useEvmWalletTokenBalances({address})
useEffect(() => {
if (addy) {
fetch({
address: addy,
});
}
}, [addy]);
useEffect(() => {
if (error) {
console.log(error);
}
}, [error]);
return (
<div>
<button onClick={handleAuth}> </button>
{/* <button onClick={signOut}></button> */}
<h3>Wallet: {addy}</h3>
<h3>Native Balance: {nativeBalance?.balance.ether} ETH</h3>
{/* <h3>All Balance: {allBalance} ETH</h3> */}
</div>
);
}
export default HomePage;