Skip to content

[Feature]: Return walletState from useConnectWallet's connect function #1209

@TadejPolajnar

Description

@TadejPolajnar

Is your request related to a problem?

I made a hook which handles all my web3 logic inside and wrapped connect function with my own function to handle additional stuff on connect.
The problem is that once the wallet is connected, the wallet state inside handleConnect will still be empty even though the wallet is connected.

const useWeb3 = () => {
  const [{ wallet, connecting }, connect, disconnect] = useConnectWallet();

  const handleConnect = async () => {
    await connect();
    console.log(wallet); // Throws null after successful connect

    // ...some additional logic
  };
};

Feature Description

Since useConnectWallet hook is just a wrapper around @web3-onboard/core the solution is pretty straight forward. Function called inside connect function already returns the WalletState, it just needs to be returned from connect function.

  const connect = useCallback(async (options?: ConnectOptions) => {
    setConnecting(true)

    const walletState = await connectWallet(options)

    setConnecting(false)
  
    return walletState;
  }, [])

Callback will then return WalletState which could be used like this:

  const handleConnect = async () => {
    const wallet = await connect();
    console.log(wallet);
  };

Alternative Solutions/workarounds

I made an useEffect which checks if wallet is connected, but I think this is just a bad workaround

  const [{ wallet, connecting }, connect, disconnect] = useConnectWallet();

  useEffect(() => {
    if (wallet) {
      // Do some stuff
    }
  }, [wallet]);

Or even more error proof, but requires two unnecessary re-renders:

  const [shouldTrigger, setShouldTrigger] = useState<boolean>(false);
  const [{ wallet, connecting }, connect, disconnect] = useConnectWallet();

  const handleConnect = async () => {
    await connect();
    setShouldTrigger(true);
  };

  const onConnect = useCallback(() => {
    console.log(wallet); // Works!!
  }, [wallet]);

  useEffect(() => {
    if (shouldTrigger) {
      onConnect();
      setShouldTrigger(false);
    }
  }, [onConnect, shouldTrigger]);

Anything else?

No response

Metadata

Metadata

Labels

featureNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions