-
Notifications
You must be signed in to change notification settings - Fork 541
Description
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