Build Web3.js Connect Wallet Button with Persisting Connection on Page Refresh

Here is a tutorial (with source code) on how to build a simple MetaMask connect wallet button with persisting connection on page refresh that you often see on Blockchain DApp websites.

Tutorial

1. To start with, create a new react app.

npx create-react-app YOUR_APP_NAME

2. To interact with Ethereum network, we need to install Web3.js library. Open up a console and execute using the following command.

npm install web3

3. If done, the project structure will look like the following.

4. Add the following code in your App.js file.

import { useState, useEffect } from 'react';
import Web3 from 'web3';

function App() {
  const [isConnected, setIsConnected] = useState(false);
  const [userInfo, setUserInfo] = useState({});

  useEffect(() => {
    checkConnectedWallet();
  }, []);

  function checkConnectedWallet() {
    const userData = JSON.parse(localStorage.getItem('userAccount'));
    if (userData != null) {
      setUserInfo(userData);
      setIsConnected(true);
      onConnect();
    }
  }

  const detectCurrentProvider = () => {
    let provider;
    if (window.ethereum){
      provider = window.ethereum;
    }
    else if (window.web3){
      provider = window.web3.currentProvider;
    }
    else {
      console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
    }
    return provider;
  };

  const onConnect = async () => {
    try {
      const currentProvider = detectCurrentProvider();
      if (currentProvider) {
        if (currentProvider !== window.ethereum) {
          console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
        }
        await currentProvider.request({ method: 'eth_requestAccounts' });
        const web3 = new Web3(currentProvider);
        const userAccount = await web3.eth.getAccounts();
        const networkId = await web3.eth.net.getId();
        const account = userAccount[0];
        let ethBalance = await web3.eth.getBalance(account);
        ethBalance = web3.utils.fromWei(ethBalance, 'ether');
        saveUserInfo(ethBalance, account, networkId);
        if (userAccount.length === 0) {
          console.log('Please connect to MetaMask');
        }
      }
    } catch (err) {
      console.log(err);
    }
  };

  const onDisconnect = () => {
    window.localStorage.removeItem('userAccount');
    setUserInfo({});
    setIsConnected(false);
  };

  const saveUserInfo = (ethBalance, account, networkId) => {
    const userAccount = {
      account: account,
      balance: ethBalance,
      connectionid: networkId,
    };
    window.localStorage.setItem('userAccount', JSON.stringify(userAccount));
    const userData = JSON.parse(localStorage.getItem('userAccount'));
    setUserInfo(userData);
    setIsConnected(true);
  };

  return (
    <div className="app">
      <div className="app-header">
        <h1>React DApp Authentication with Web3.js and MetaMask</h1>
      </div>
      <div className="app-wrapper">
        {!isConnected && (
          <div>
            <button onClick={onConnect}>
              Connect to MetaMask
            </button>
          </div>
        )}
      </div>
      {isConnected && (
        <div className="app-wrapper">
          <div className="app-details">
            <h2>✅ You are connected to metamask.</h2>
            <div>
              <b>Account number:</b>{userInfo.account}
            </div>
            <div>
              <b>Balance:</b>{userInfo.balance}
            </div>
            <div>
              <b>Connection ID:</b>{userInfo.connectionid}
            </div>
          </div>
          <div>
            <button onClick={onDisconnect}>Disconnect</button>
          </div>
        </div>
      )}
    </div>
  );
}

export default App;

5. Open up a console and execute using the following command to start the react project.

npm start

6. Here is the results:

Also read:

Ambiz Education Search:

error: