1
import { useConnection} from '@solana/wallet-adapter-react';

const { connection } = useConnection();

here, how do we change the connection network? Is there any method like setConnection or something similar?

1 Answer 1

0

You set the network usually in the ConnectionProvider with the endpoint prop.

  // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
  const network = WalletAdapterNetwork.Mainnet;

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

  const wallets = useMemo(
    () => [
      new SolflareWalletAdapter(),
      new PhantomWalletAdapter(),
      new GlowWalletAdapter(),
      new LedgerWalletAdapter(),
    ],
    []
  );

  return (
    <ConnectionProvider endpoint={endpoint}>
      <WalletProvider wallets={wallets} autoConnect>
        <WalletModalProvider>{children}</WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
};```

And instead of useConnection, you can also define it yourself.

```import { Connection } from '@solana/web3.js';```

And then set the connection

```const connection = new Connection('https://api.devnet.solana.com', "confirmed")

2
  • Yeah, but what's really the point of useConnection hook if we can just initialize a new connection object ourselves everytime and the endpoint is not changable in the ConnectionProvider? I'm using some other packages and they use useConnection hook, so I can't use my own connection object
    – Gmer
    Commented Aug 18, 2022 at 20:10
  • It is changeable. The network variable will allow you to change between devnet, testnet and mainnet. If you want to use your own rpc, just adapt the endpoint so it points to your rpc url. Commented Aug 18, 2022 at 20:18

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.