Search code examples
reactjsconditional-statementsmetamask

React-js: briefly wrong div loaded in conditional rendering


The following script allows the react-app to connect to Metamask, then show the homepage; moreover, if the user is already connected

walletAddress.length>0

, we want to show directly the homepage. (I simplified the code to make it clearer)

function App() {
  const [walletAddress, setWallet] = useState("");

  useEffect(() => {
    rememberWallet();
    addWalletListener();
  }, []);

  const connectWalletPressed = async () => {
    const obj = await getCurrentWalletConnected('eth_requestAccounts')
    setWallet(obj.address);
};

async function rememberWallet(){
    const obj = await getCurrentWalletConnected('eth_accounts')
    setWallet(obj.address)
}


function addWalletListener() {
    window.ethereum.on("accountsChanged", (accounts) => {
        if (accounts.length > 0) {
            setWallet(accounts[0]);
        } else {
            setWallet("");
        }
    });
}
  console.log(walletAddress)
  return (
    walletAddress.length>0 ?
    <div>HOME PAGE</div>:
    <div><button id="walletButton" onClick={connectWalletPressed}>PRESS TO CONNECT METAMASK</button> </div>
  );
}

export default App;

The point is: when the user is already connected, the second is rendered for a moment.

I really appreciate any suggestionùthanks


Solution

  • Thanks to @Hozeis, We found a workaround using a time-out of 50 ms showing a blank page.

    function App() {
        const [walletAddress, setWallet] = useState("");
        const [loading, setLoading] = useState(true); 
      
        useEffect(() => {
          rememberWallet();
          addWalletListener();
          setTimeout(() => setLoading(false), 50); //time-out required to assess myContext.walletAddress.length>0 ?
        }, []);
      
        const connectWalletPressed = async () => {
          const obj = await getCurrentWalletConnected('eth_requestAccounts')
          setWallet(obj.address);
      };
      
      async function rememberWallet(){
          const obj = await getCurrentWalletConnected('eth_accounts')
          setWallet(obj.address)
      }
      
      
      function addWalletListener() {
          window.ethereum.on("accountsChanged", (accounts) => {
              if (accounts.length > 0) {
                  setWallet(accounts[0]);
              } else {
                  setWallet("");
              }
          });
      }
      if (loading) {
        return null
    }
    
        return (
          walletAddress.length>0 ?
          <div>HOME PAGE</div>:
          <div><button id="walletButton" onClick={connectWalletPressed}>PRESS TO CONNECT METAMASK</button> </div>
        );
      }
      
      export default App;