6

I'm currently creating a react+typescript website with Solana Wallet Adapter. I have routes setup and I want to keep the wallet connected when I go between pages or when I'm reloading the page. I know I can use the autoconnect but I want to keep the connection on and the publickey to be in localstate. Do you know if this is possible and how?

1
  • you might get better engagement by supplying code snippets
    – trent.sol
    Commented Aug 17, 2022 at 21:06

1 Answer 1

1

Your Routes should be inside the wallet context, so first write the Wallet component:

import React, { useMemo } from 'react';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';
import {
    WalletModalProvider,
    WalletDisconnectButton,
    WalletMultiButton
} from '@solana/wallet-adapter-react-ui';
import { clusterApiUrl } from '@solana/web3.js';

// Default styles that can be overridden by your app
require('@solana/wallet-adapter-react-ui/styles.css');

export function Wallet({ children }: any) {
    // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
    const network = WalletAdapterNetwork.Devnet;

    // You can also provide a custom RPC endpoint.
    const endpoint = useMemo(() => clusterApiUrl(network), [network]);

    const wallets = useMemo(
        () => [
            new PhantomWalletAdapter(),
        ],
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [network]
    );

    return (
        <ConnectionProvider endpoint={endpoint}>
            <WalletProvider wallets={wallets} autoConnect>
                <WalletModalProvider>
                    <WalletMultiButton />
                    <WalletDisconnectButton />
                    { /* Your app's components go here, nested within the context providers. */}
                    {children}
                </WalletModalProvider>
            </WalletProvider>
        </ConnectionProvider>
    );
};

And then write the Routes inside the Wallet component:

import './App.css';
import { Wallet } from './components/Wallet';
import {
  Routes,
  Route,
  Link,
  HashRouter as Router,
} from "react-router-dom";
import { Home } from './pages/Home';

function App() {
  return (
    <div className="App">
      <Router>
        <Wallet>
          <Link to="/">Home</Link>
          <Routes>
            <Route path="/" element={<Home />} />
          </Routes>
        </Wallet>
      </Router>
    </div>
  );
}

export default App;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.