Switching Accounts
Account switching is performed exclusively through the wallet interface, there is no programmatic method to change accounts.
WalletConnect provides two methods for monitoring account changes:
- Observe the walletAddress property using React effect.
- Register an event listener on the walletInstance.
Observe the walletAddress Property
Observe walletAddress property using React effects. This property returns null when disconnected and updates when:
- A wallet connection is established.
- The network changes.
- The wallet disconnects.
- The user switches accounts through the wallet interface.
The following code demonstrates how to listen to account changes with WalletConnect:
Monitoring account changes with WalletConnectreact
import { useWalletConnect } from "@btc-vision/walletconnect";
function App() {
const {connectToWallet, walletAddress, walletInstance} = useWalletConnect()
useEffect(() => {
if (walletAddress) {
console.log("Connected to wallet: ", walletAddress);
}
}, [walletAddress]);
return (
<button onClick={async () => { await connectToWallet('OP_WALLET')} } >Connect to OP_WALLET</button>
)
}Register an Event Listener
Call the on() method on the walletInstance to register a listener for account change events. Remove the listener with removeListener() when no longer needed. Note that the event name is specific to each wallet provider.
The following code demonstrates how to listen to account changes using the walletInstance. This example registers a listener for the accountsChanged event, which is an OPWallet event:
Register an accountsChanged event listenerreact
import { useWalletConnect } from "@btc-vision/walletconnect";
function App() {
const {connectToWallet, walletInstance} = useWalletConnect()
const accountChanged = useCallback((accounts: string[]) => {
// Do something knowing accounts changed
console.log("AccountChanged", accounts)
}, []);
useEffect(() => {
if (walletInstance) {
walletInstance.on("accountsChanged", accountChanged);
return () => {
walletInstance.removeListener("accountsChanged", accountChanged);
};
}
}, [walletInstance, accountChanged]);
return (
<button onClick={async () => { await connectToWallet('OP_WALLET')} } >Connect to OP_WALLET</button>
)
}