如何在Next.js中使用hooks来处理rainbowkit和wagmi?

huangapple go评论72阅读模式
英文:

How to use hooks in nextJs for rainbowkit and wagmi?

问题

在这段代码中,我想要在我的用户界面上显示tokenbalance和nativebalance。

我正在使用wagmi和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.formatted} {balance.symbol}
        </p>
      )}
      {tokenBalance && (
        <p>
          代币余额{tokenBalance.formatted} {tokenBalance.symbol}
        </p>
      )}
    </div>
  );
};

export default WalletPage;

当我在Metamask中切换帐户时,在ConnectButton模块上一切正常,但在我的用户界面中,我必须手动刷新才能获取tokenablance,我知道在使用hooks时不应该这样做。那么,正确使用wagmi hooks的方法是什么?

我需要在Metamask中更改帐户时在我的用户界面上获取tokenBalance和native balance。

英文:

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

I#m using wagmi and rainbowkit

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

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

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

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

    fetchData();
  }, []);

  return (
    &lt;div&gt;
      &lt;ConnectButton /&gt;
      {balance &amp;&amp; (
        &lt;p&gt;
          Balance: {balance.formatted} {balance.symbol}
        &lt;/p&gt;
      )}
      {tokenBalance &amp;&amp; (
        &lt;p&gt;
          Token Balance: {tokenBalance.formatted} {tokenBalance.symbol}
        &lt;/p&gt;
      )}
    &lt;/div&gt;
  );
};

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

得分: 1

因为您的useEffect依赖项没有设置为监听帐户更改,所以出现了这个问题。当您使用[]时,告诉useEffect只运行一次。如果您希望它再次运行,应确保添加一个依赖项,以便当依赖项的值发生更改时,会再次触发useEffect

也许您可以尝试类似以下的方式:

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

这将导致useEffectaccount.address发生更改时再次运行。但是,请注意,在这样做时要小心。这可能会导致您的效果多次触发,因此在再次获取之前,将当前地址的副本保存在状态中,并在if条件中检查该值可能是个好主意。

英文:

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(() =&gt; { ... }, [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.

huangapple
  • 本文由 发表于 2023年5月29日 22:47:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定