This is happening due to a refresh of the website when click on connect wallet button, it pops up the metamask, there it will print the console log which you have written inside the function but when our wallet connects to the metamask then the page refresh and it resets the state.
So to overcome this issue, there are multiple ways to handle it or to preserve the state.
I have used useEffect which runs functions on every refresh, where it will check whether the user has metamask installed and is the user's wallet is connected to the metamask. useEffect will run on every refresh, so even if the page refreshes, we will run 1 more function to check whether our wallet is connected or not and accordingly we will get the correct status or updated states of wallet. Please refer below code
const [currentAccount, setCurrentAccounts] = useState("");
const [wallets, setWallets] = useState([]); //for you
//Connect to wallet
const connectWallet = async () => {
try {
const accounts = await ethereum?.request({
method: "eth_requestAccounts",
});
setCurrentAccounts(accounts[0]);
setWallets(accounts) //for you
window.location.reload(); // i am forcing window to be refresh so that i can run the useEffect to run all my functions which are need to be run after connecting to wallet.
} catch (error) {
if (error.code === 4001) {
console.log("User rejected the request");
}
throw new Error("No Ethereum object.");
}
};
useEffect(() => {
const checkIfWalletIsConnected = async () => {
try {
const accounts = await ethereum.request({ method: "eth_accounts" })
if (accounts.length) {
setCurrentAccounts(accounts[0]);
setWallets(accounts) // for you
} else {
console.log("No Account Found");
}
} catch (error) {
console.log("No Ethereum Found");
}
};
const checkIfMetamaskInsalled = () => {
if (!ethereum) {
return setMetamaskInstalled(false);
} else {
return setMetamaskInstalled(true);
}
};
checkIfMetamaskInsalled();
checkIfWalletIsConnected();
}, []);