-3

In this code I want to display tokenbalance and nativebalance on my UI

I#m using wagmi and rainbowkit

import React, { useEffect, useState } from 'react';
import { ConnectButton } from '@rainbow-me/rainbowkit';
import { fetchBalance,getAccount } from '@wagmi/core';
import type { NextPage } from 'next';

const WalletPage: NextPage = () => {
  const account = getAccount()
  const [balance, setBalance] = useState();
  const [tokenBalance, setTokenBalance] = useState();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const balanceData = await fetchBalance({
          address: account.address,
        });
        setBalance(balanceData);

        const tokenBalanceData = await fetchBalance({
          address: account.address,
          token: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
        });
        setTokenBalance(tokenBalanceData);
      } catch (error) {
        console.error(error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <ConnectButton />
      {balance && (
        <p>
          Balance: {balance.formatted} {balance.symbol}
        </p>
      )}
      {tokenBalance && (
        <p>
          Token Balance: {tokenBalance.formatted} {tokenBalance.symbol}
        </p>
      )}
    </div>
  );
};

export default WalletPage;

When i change accounts in metamask, on the connectButton module everything works but in my UI i have to manually refresh to get the tokenablance and i know i shouldnt have to do this when using hooks. So whats the proper way of using wagmi hooks?

I need to get tokenBalance and native balance on my ui when cahnging accounts in metamask

1 Answers1

1

It's because you're useEffect dependencies are not setup to listen to changes in accounts. When you use [], you tell the useEffect to run once. if you want this to run again, you should make sure to add a dependency so that when the value for that dependency changes, it causes your useEffect to trigger again.

Maybe you could try something like;

useEffect(() => { ... }, [account.address])

This will cause the useEffect to run again if account.address changes.Be careful when doing this, however. It could cause your effect to trigger multiple times, so it might be a good idea to keep a copy of your current address in state and check against that value in an if condition before fetching again.

Mark Barton
  • 847
  • 6
  • 15
  • ok, makes sense, now how do i fix this? – oaschpartie May 29 '23 at 14:51
  • I appreciate your help, but can you at least post the whole code or at least more than this 1 line here – oaschpartie May 29 '23 at 14:53
  • I shouldn't need to post the whole code. I am simply answering your question. You asked how you can get the fetch to re-run when you change accounts. I have shown you how. It is up to you to make the changes. At the very least, I could have pointed you to another SO post that discusses dependencies within useEffects. – Mark Barton May 29 '23 at 14:55
  • If you like I could mark this question as duplicate? I've given you the solution to your problem. I've explained why it's not working, what you need to change, potential gotchas, and solutions to those gotchas. Short of writing an entire block of code, I don't see what you would stand to gain. If you're unable to identify the solution based on what I have told you then you clearly do not have a solid enough grasp of the fundamentals of React. – Mark Barton May 29 '23 at 15:03
  • But one line is literally all you have to change... – Mark Barton May 29 '23 at 15:10
  • than at least post the whole line, cause applying your solution doesnt do anything. If its 1 line of code post instead of going back and forth – oaschpartie May 29 '23 at 15:13
  • I offer a third perspective - kind of in the middle. A post with an explanation of what goes wrong and a hint at a solution is definitly enough for being considered an answer according to StackOverflow goals (i.e. [answer]). But on the other hand, if an answer is of obviously improveable helpfulness by one more detailed line of code, then it probably loses some potential upvotes. (I assume that one line would not require info which is unavailable in the question...., sorry if that shows lack of insight on my part....). A polite (hint hint) request for such code would be OK. – Yunnosch May 29 '23 at 15:35