Reputation: 119
I've just started to use walletConnect web3Modal to handle my clients' ethereum wallet connections. Out authentication process is something like this:
The problem is useWeb3Modal hook returns an async function called open(); Which is resolved when the modal is opened (Not when wallet is connected successfully)
Now I want to write a hook which handles this login logic for me. The problem is if client's wallet is not connected to my app, I can't request server after successful wallet connection since there's no state which defines wallet connection state.
Here's my code:
import {useAccount, useSigner} from "wagmi";
import signMessage from "@/modules/auth/services/signMessage";
import type {Signer} from "@wagmi/core";
import {useWeb3Modal} from "@web3modal/react";
const useLogin = (): () => void => {
const {isConnected, isConnecting, isReconnecting, address} = useAccount();
const {open} = useWeb3Modal();
const signer = useSigner();
return () => {
console.log(`isConnected: ${isConnected} isConnecting: ${isConnecting} isReconnecting: ${isReconnecting} address: ${address}`)
if (!isConnected && !isConnecting && !isReconnecting) {
open().then(console.log);
return;
}
signMessage(address as string, signer.data as Signer).then(accessToken => {
console.log(accessToken);
});
};
}
export default useLogin;
And the way I use this hook is something like this:
import {Button} from "@mui/material";
import {useWeb3Modal} from "@web3modal/react";
import useLogin from "../hooks/useLogin";
const Home = (props) => {
const login = useLogin(); //The hook I've written above
const {open} = useWeb3Modal();
return (
<>
<Button variant="contained" onClick={() => login()} disableElevation>Connect wallet</Button>
</>
)
}
Any ideas how to handle it?
Upvotes: 2
Views: 1123
Reputation: 1
Actually i found a cleaner way to call a function when wallet is connected.
import {useAccount} from "wagmi";
const App = (props) => {
const { isConnected, address } = useAccount({
onConnect: ({ address, connector }) => console.log("Connected. address:"+address),
});
}
Upvotes: 0