Here’s an example of using the getBalance method to get the balance of the connected user’s wallet

import { useEffect, useState } from 'react';

import {
  useDynamicContext,
  DynamicContextProvider,
  UserProfile,
  useIsLoggedIn,
} from '@dynamic-labs/sdk-react-core';

const Home = () => {
  const { user, handleLogOut, setShowAuthFlow, primaryWallet } =
    useDynamicContext();

  const isLoggedIn = useIsLoggedIn();

  const [balance, setBalance] = useState<string | null>(null);

  useEffect(() => {
    primaryWallet?.getBalance().then((balance) => {
      if (balance) {
        setBalance(balance.toString());
      }
    });
  }, [primaryWallet]);

  if (isLoggedIn) {
    return (
      <div>
        <p>User is logged in</p>
        { primaryWallet && <>}
          <p>Address: {primaryWallet.address}</p>
          <p>Balance: {balance}</p>
        </>}
        <button type='button' onClick={handleLogOut}>
          Log Out
        </button>
      </div>
    );
  }

  return (
    <div>
      <button type='button' onClick={() => setShowAuthFlow(true)}>
        Connect With My Wallet
      </button>
    </div>
  );
};

const App = () => (
  <DynamicContextProvider
    settings={{
      appLogoUrl:
        'https://upload.wikimedia.org/wikipedia/commons/3/34/Examplelogo.svg',
      appName: 'Example App',
      environmentId: 'REPLACE_WITH_YOUR_ENV_ID',
      onAuthSuccess: ({
        user,
      }: {
        user: UserProfile;
      }) => {
        console.log(
          `Welcome ${user.email}`,
        );
        window.location.assign('/success');
      },
    }}
  >
    <Home />
  </DynamicContextProvider>
);

export default App;

Was this page helpful?