Skip to main content

useSwitchAccount

The useSwitchAccount hook is a mutation hook for establishing a connection to a specific wallet.

Live Editor
function withProviders(
    Component: React.FunctionComponent<object>,
    walletProviderProps?: Omit<ComponentProps<typeof WalletProvider>, 'children'>,
) {
    // Work around server-side pre-rendering
    const queryClient = new QueryClient();
    const networks = {
        testnet: { url: getFullnodeUrl('testnet') },
    };

    return () => {
        const [shouldRender, setShouldRender] = useState(false);
        useEffect(() => {
            setShouldRender(true);
        }, [setShouldRender]);

        if (!shouldRender) {
            return null;
        }

        return (
            <QueryClientProvider client={queryClient}>
                <IotaClientProvider networks={networks}>
                    <WalletProvider {...walletProviderProps}>
                        <Component />
                    </WalletProvider>
                </IotaClientProvider>
            </QueryClientProvider>
        );
    };
}

const UseSwitchAccountExample = withProviders(() => {
    const { mutate: switchAccount } = useSwitchAccount();
    const accounts = useAccounts();

    return (
        <div style={{ padding: 20 }}>
            <ConnectButton />
            <ul>
                {accounts.map((account) => (
                    <li key={account.address}>
                        <button
                            onClick={() => {
                                switchAccount(
                                    { account },
                                    {
                                        onSuccess: () =>
                                            console.log(`switched to ${account.address}`),
                                    },
                                );
                            }}
                        >
                            Switch to {account.address}
                        </button>
                    </li>
                ))}
            </ul>
        </div>
    );
});

render(<UseSwitchAccountExample/>)
Result
Loading...

Arguments

  • args - Arguments passed to the connect function of the wallet.

    • account - The account to switch to.
  • options - Options passed the useMutation hook from @tanstack/react-query.