Skip to main content

onEvent

Adds an event listener for Dynamic client events. Use this to react to authentication state changes, wallet updates, and other client events.

Usage

import { onEvent } from '@dynamic-labs-sdk/client';

const removeListener = onEvent({
  event: 'walletAccountsChanged',
  listener: ({ walletAccounts }) => {
    console.log('Wallet accounts changed:', walletAccounts);
  },
});

// Later, remove the listener when done
removeListener();

Parameters

ParameterTypeDescription
eventstringThe event name to listen for.
listenerFunctionThe callback function to execute when the event fires.
clientDynamicClient (optional)The Dynamic client instance. Only required when using multiple clients.

Returns

() => void - A function that can be called to remove the listener.

Examples

Track wallet account changes

import { useEffect } from 'react';
import { onEvent } from '@dynamic-labs-sdk/client';

const WalletTracker = () => {
  useEffect(() => {
    const removeListener = onEvent({
      event: 'walletAccountsChanged',
      listener: ({ walletAccounts }) => {
        console.log('Current wallets:', walletAccounts.length);
        walletAccounts.forEach((wallet) => {
          console.log(`- ${wallet.address} (${wallet.chain})`);
        });
      },
    });

    return () => {
      removeListener();
    };
  }, []);

  return <div>Tracking wallet changes...</div>;
};

Multiple event listeners

import { onEvent } from '@dynamic-labs-sdk/client';

const setupEventListeners = () => {
  const removeWalletListener = onEvent({
    event: 'walletAccountsChanged',
    listener: ({ walletAccounts }) => {
      updateWalletUI(walletAccounts);
    },
  });

  const removeAuthListener = onEvent({
    event: 'logout',
    listener: () => {
      clearUserSession();
    },
  });

  // Return cleanup function
  return () => {
    removeWalletListener();
    removeAuthListener();
  };
};

Common Events

EventDescription
initStatusChangedFired when client initialization status changes
logoutFired when user logs out
tokenChangedFired when token (jwt) changes
userChangedFired when user changes
walletAccountsChangedFired when wallet accounts change