I’m building a dapp, and for some reason, I can’t successfully connect wallets on mobile. It is working perfectly on desktop.
import './App.css'
import { useState, useEffect } from 'react';
function TestButton() {
const [currentAccount, setCurrentAccount] = useState(null);
const { ethereum } = window;
const checkWalletIsConnected = async () => {
if (!ethereum) {
console.log("Make sure you have a crypto wallet installed!");
alert("Please install a crypto wallet!");
return;
} else {
console.log("Wallet exists. We're ready to go!");
}
const accounts = await ethereum.request({ method: 'eth_accounts'});
const networkId = await ethereum.request({ method: 'net_version'});
if (accounts.lenght !==0) {
if(networkId !== "4"){
setCurrentAccount(null);
alert("Please change to Rinkeby Network.");
console.log("Wrong network");
} else {
const account = accounts[0];
console.log("Found an authorized account: ", account);
setCurrentAccount(account);
}
} else {
console.log("No authorized account found")
}
};
const connectWalletHandler = async () => {
if (!ethereum) {
alert("Please install a crypto wallet!");
}
try {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const networkId = await ethereum.request({ method: 'net_version'});
if(networkId !== "4"){
setCurrentAccount(null);
console.log("Wrong network");
}else{
console.log("Found an account! Address: ", accounts[0]);
setCurrentAccount(accounts[0]);
}
} catch (err) {
console.log(err)
}
};
const connectWalletButton = () => {
return (
<button onClick={connectWalletHandler} className='connect-w-button'>
Connect your wallet
</button>
)
};
const workedText = () => {
return (
<div>
Hello, it worked.
</div>
)
};
useEffect(() => {
checkWalletIsConnected();
if (ethereum) {
ethereum.on('accountsChanged', function (accounts) {
console.log("Address has been changed");
checkWalletIsConnected();
});
ethereum.on('chainChanged', function (networkId) {
console.log("Network ID Changed");
checkWalletIsConnected();
});
}else{
console.log("Install Crypto Wallet");
}
}, [])
return (
<div>
{currentAccount ? workedText() : connectWalletButton()}
</div>
);
}
export default TestButton
On MetaMask’s Mobile Browser its showing wrong network alert before/after wallet is connected. I reviewed my code several times and can’t find anything. Any suggestions?