I'm trying to add a balance of USDC in a connected wallet that updates on a nextjs typescript website. I want to add it to my SOL balance context provider or do I need to make a completely separate context for the USDC balance?
import { useWallet } from '@solana/wallet-adapter-react';
import { LAMPORTS_PER_SOL } from '@solana/web3.js';
import { createContext, useContext, useEffect, useState, useMemo } from 'react';
import * as anchor from '@project-serum/anchor';
const BalanceContext = createContext(null);
const rpcHost = process.env.NEXT_PUBLIC_SOLANA_RPC_HOST;
const connection = new anchor.web3.Connection(rpcHost);
export default function useWalletBalance() {
const { balance, walletPubKey, walletAddress } = useContext(BalanceContext);
return { balance, walletPubKey, walletAddress };
}
export const WalletBalanceProvider = ({ children }) => {
const wallet = useWallet();
const [balance, setBalance] = useState(0);
const [walletPubKey, setWalletPubKey] = useState({});
const [walletAddress, setWalletAddress] = useState('');
const anchorWallet = useMemo(() => {
if (
!wallet ||
!wallet.publicKey ||
!wallet.signAllTransactions ||
!wallet.signTransaction
) {
return;
}
return {
publicKey: wallet.publicKey,
signAllTransactions: wallet.signAllTransactions,
signTransaction: wallet.signTransaction,
};
}, [wallet]);
const refreshWallet = async () => {
if (!anchorWallet) {
setBalance(0);
setWalletAddress('');
setWalletPubKey({});
return;
}
try {
const balance = await connection.getBalance(anchorWallet.publicKey);
setBalance(balance / LAMPORTS_PER_SOL);
setWalletPubKey(anchorWallet.publicKey);
setWalletAddress(anchorWallet.publicKey.toBase58());
} catch (e) {
console.error(e);
}
};
useEffect(() => {
refreshWallet();
}, [anchorWallet, balance, walletAddress]);
return (
<BalanceContext.Provider value={{ balance, walletPubKey, walletAddress }}>
{children}
</BalanceContext.Provider>
);
};
Not sure the best way to include it in refresh async function.