Problem connecting wallets on Mobile

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?

1 Like

Hi @ppm.eth ,

Check out these Mobile section of the MetaMask docs here -

1 Like

I did actually, but no success.

2 Likes

I also tried to detect the mobile provider manually as mentioned there, but the same error persists.

2 Likes

@ppm.eth

Hi, I’m facing the same problem, here’s a solution. You need to manually define the mobile device (in my ios version)

function isMobileDevice() {
  return "ontouchstart" in window || "onmsgesturechange" in window;
}

Next we need to create a url for our application using MetaMask:

 const dappUrl = "thisWillBeYourUniqueWEB3URL";
 const metamaskAppDeepLink = "https://metamask.app.link/dapp/" + dappUrl;

Then you need to add the following code:

                <Button
                    onClick={() => {
                      if (isMobileDevice()) {
                        window.open(metamaskAppDeepLink);
                      } else {
                        window.open("https://metamask.io/", "_blank");
                      }
                    }}
                 >Click me</Button>

I can’t attach a link here to my github, where a separate thread shows the solution to this problem :zipper_mouth_face:
And by the way, putting ‘accountsChanged’ and ‘chainChanged’ methods in a hook useEffect is a big performance hit due to re-rendering.

4 Likes

Thank you for your reply @snwlprd.eth .

That will make my dapp to open from Safari to MetaMask’s Browser right?
But my problem is inside the app’s browser already.

I just tested with Coinbase’s browser and it is working, but MetaMask isn’t. I’m confused.

3 Likes

@ppm.eth

Please describe the problem in more detail if you can. Do you have error logs?

1 Like

I don’t have any log because I did not setup a local development server to debug mobile.

But for some reason on MetaMask’s app, the connection is stuck here:

if(networkId !== "4"){
            setCurrentAccount(null);
            alert("Please change to Rinkeby Network.");
            console.log("Wrong network");
        }

The alert opens before and after the Connect your wallet button is pressed.

On desktop everything is running smoothly without any console errors.

3 Likes

Did you get the dapp url right?

Try to define the provider and hang a handler on it.

const provider = await detectEthereumProvider();

const setListener = provider => {
provider.on(“chainChanged”, _ => window.location.reload());
};

also can you sandbox this or provide a repository ?

4 Likes

I tried to post a Sandbox but can’t post links…

I will try the handler.

2 Likes

Did you try? or havent yet

Same thing :face_with_diagonal_mouth:
Any tips?

1 Like

Need some error logs to better understand the issue

1 Like

I’ll try to log something and I’ll let you guys know. From what I read I’ll have to build MetaMask’s app locally in order to debug.

Hey @ppm.eth ,

Just to throw it out there, making sure you’ve also checked out MetaMask Flask? https://metamask.io/flask/

1 Like

I did not know about this feature. Can we mobile log from there?

Hi @ppm.eth ,

There is no mobile version of Flask, my bad.