Search code examples
javascriptreactjsreact-hooksmetamask

How can I display the metamask address on the webpage dynamically using react


I can actually get the address of metamask account but everytime I change the account in metamask the specific component seems not to be rendering again I don't know what to add in array parameter of useEffect so that to reflect changes in my account on the webpage without reloading. Here is the useState and useEffect defined in the app.js.

I have already implemented the Metamask connecting functionality.

JavaScript

const [account, setAccount] = useState(null)        // useState functionality

useEffect(() => {                                   // useEffect functionality
    const getaccount = async()=>{
      const accounts = await window.ethereum.request({method:'eth_accounts'});
      setAccount(accounts[0].toUpperCase())
    }
  
    getaccount();
  }, [])

HTML

return (
    <div className="App">
      <header className="App-header">
        <h1>First Dapp Application</h1>
        <p>Our account address is: {account ? account:"not connected"}</p>
      </header>
    </div>
  );

Output

enter image description here


Solution

  • I haven't tested this code, but basically, you need to add a listener when there is a change in the accounts with this code on a first page load hook:

    window.ethereum.on('accountsChanged', function (accounts) {
      setAccount(accounts[0].toUpperCase());
    });
    

    I'm not an expert with react, but I think you could add another useEffect() for initialization purpose like so:

    useEffect(() => {
        window.ethereum.on('accountsChanged', function (accounts) {
            setAccount(accounts[0].toUpperCase());
        });
    }, []);