I’m trying to redirect the user to onboard
page when he successfully connects to his wallet. Web3Button is not returning anything.
How to do that? I’m stuck here.
import React, { useEffect } from "react";
import { Web3Button } from "@web3modal/react";
import { useProvider } from "wagmi";
import { useRouter } from "next/router";
const Hero = () => {
const router = useRouter();
const provider = useProvider();
const handleConnect = async () => {
try {
if (provider) {
router.push("/onboard");
}
} catch (error) {
console.log(error);
}
};
return (
<main className="container mx-auto">
<div className="flex flex-col flex-wrap items-center space-y-6 justify-center h-[70vh]">
<h2 className="text-2xl px-4 text-center md:text-4xl sm:text-3xl lg:text-5xl font-bold ">
Title
</h2>
<p className="px-4 text-center text-md md:text-xl lg:text-2xl">
Description
</p>
<Web3Button />
</div>
</main>
);
};
export default Hero;
2
Answers
It seems that you want to redirect the user to the
/onboard
page when they successfully connect to their wallet using theWeb3Button
component. However, theWeb3Button
component does not provide any callback or return value when the user connects their wallet. Therefore, you need to use a different approach to detect when the user has successfully connected their wallet and then redirect them to the/onboard
page.One way to achieve this is by using the
useEffect
hook to listen for changes in theprovider
variable, which will be updated when the user connects their wallet. When theprovider
variable changes, you can check if it is truthy (i.e., the user has connected their wallet) and then redirect them to the/onboard
page using therouter.push
method.Here’s how you can modify your code to achieve this:
In this modified code, we added a new state variable
isConnected
to keep track of whether the user has connected their wallet or not. We also added twouseEffect
hooks: the first one listens for changes in theprovider
variable and sets theisConnected
state variable to true if it is truthy; the second one listens for changes in theisConnected
state variable and redirects the user to the/onboard
page if it is true.We also added an
onClick
prop to theWeb3Button
component and defined thehandleConnect
function, which you can use to perform any actions you need before redirecting the user to the/onboard
page.You are connected to metamask when you get the accounts from metamask with
if you get accounts that means you are connected
But I dont think that connected to metamask is enough, you should also add logic to see if connected network is correct network and then you should redirect the user