0

I use react !

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

It did not work. there is no console.log.

I think browser doesn't know account changed.

and is there anyway that I can notice when my wallet locked ? window.ethereum._metamask.isUnlocked() is deprecated function :(


const checkIfAccountChanged = async () => {
    try {
      ethereum.on('accontsChanged', accounts => {
        console.log('connected', accounts[0]);
        saveWalletAddress(accounts[0]);
      });
    } catch (error) {
      console.log(error);
    }
  };

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

I update code !


enter image description here

I connect one wallet.

enter image description hereHi my dapp doesn't detect when metamask account changed or locked.

I click '연결' means not connected. browser doesnt know


This is full code

const App = () => {
  const { value: isLoading, setValue: setIsLoading } = useValue(true);
  const { walletAddress, saveWalletAddress, clearWalletAddress } = useWalletAddressStore();

  const checkIfAccountChanged = async () => {
    try {
      ethereum.on('accontsChanged', accounts => {
        console.log('connected', accounts[0]);
        saveWalletAddress(accounts[0]);
      });
    } catch (error) {
      console.log(error);
    }
  };

 useEffect(() => {
   const walletCompany = getLocalStorage('wallet');
    const connectMetamaskAuto = async () => {
      const res = await connetMetamask();
      res.address && saveWalletAddress(res.address);
      setIsLoading(false);
    };
    const connectCoinbaseAuto = async () => {
      const res = await connectCoinbase();
      res.address && saveWalletAddress(res.address);
      setIsLoading(false);
    };
    if (walletCompany) {
      walletCompany === 'metamask' ? connectMetamaskAuto() : connectCoinbaseAuto();
    } else setIsLoading(false);
  }, []);

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


const { value: isLoading, setValue: setIsLoading } = useValue(true);
  const [wallet, setWallet] = useState<string>('');
  // const { walletAddress, saveWalletAddress, clearWalletAddress } = useWalletAddressStore();

  const checkIfAccountChanged = async () => {
    try {
      ethereum.on('accontsChanged', accounts => {
        console.log('connected', accounts[0]);
        setWallet(accounts[0]);
      });
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
   const walletCompany = getLocalStorage('wallet');
    const connectMetamaskAuto = async () => {
      const res = await connetMetamask();
      res.address && saveWalletAddress(res.address);
      setIsLoading(false);
    };
    const connectCoinbaseAuto = async () => {
      const res = await connectCoinbase();
      res.address && saveWalletAddress(res.address);
      setIsLoading(false);
    };
    if (walletCompany) {
      walletCompany === 'metamask' ? connectMetamaskAuto() : connectCoinbaseAuto();
    } else setIsLoading(false);
  }, []);

  useEffect(() => {
    checkIfAccountChanged();
  }, []);
5
  • So the problem is account3 not connected right?
    – Ad-h0c
    Sep 21, 2022 at 10:22
  • After one account connected. If i connect second or third, browser doesnt know
    – Jerry
    Sep 21, 2022 at 10:24
  • Instead of custom hook const { walletAddress, saveWalletAddress, clearWalletAddress } = useWalletAddressStore(); try using useState():
    – Ad-h0c
    Sep 21, 2022 at 10:24
  • I use state not work
    – Jerry
    Sep 21, 2022 at 10:33
  • It is supposed to work like that; I am not sure why. But I have updated my full code down there. It should work this time.
    – Ad-h0c
    Sep 21, 2022 at 10:40

2 Answers 2

0

It is almost similar to your answer. Because you forgot to update the state of an account.

const [currentAccount, setCurrentAccount] = useState("");    

const checkIfAccountChanged = async () => {
        try {
          const {ethereum} = window;
          ethereum.on('accountsChanged', (accounts) => {
            console.log("Account changed to:", accounts[0]);
            setCurrentAccount(accounts[0]);
          });
    
        } catch (error) {
          console.log(error);
        }
      }

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

In the checkIfAccountChanged function, when the account changes, you need to update the state. If you log the details into the console, it will be shown only in your console.

Tell me if it helps!

EDIT:

enter image description here

Also remember, when you are changing the account, you should connect before changing it.

Like this:

enter image description here

enter image description here

In the first image, even though I have changed the account, it is not connected so it is not changed.

In the second image, you can see there is something called connect, you should click on it to really change the account.

EDIT2:

APP.js

import React, { useState, useEffect } from "react";
import { ethers } from "ethers";

export default function App() {
  const [currentAccount, setCurrentAccount] = useState("");

  const checkIfMetamaskIsInstalled = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        console.log(`Install Metamask wallet`);
      } else {
        console.log(`we have ethereum object ${ethereum}`);
      }

      const accounts = await ethereum.request({ method: "eth_accounts" });

      if (accounts.length !== 0) {
        const account = accounts[0];
        console.log("Found an authorized account:", account);
        setCurrentAccount(account);
      } else {
        console.log("No authorized account found");
      }
    } catch (error) {
      console.log(error);
    }
  };

  const checkIfAccountChanged = async () => {
    try {
      const {ethereum} = window;
      ethereum.on("accountsChanged", (accounts) => {
        console.log("Account changed to:", accounts[0]);
        setCurrentAccount(accounts[0]);
      });
    } catch (error) {
      console.log(error);
    }
  };

  const connectWallet = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        alert("get metamask!");
        return;
      }

      const accounts = await ethereum.request({
        method: "eth_requestAccounts",
      });
      console.log("connected!", accounts[0]);
      setCurrentAccount(accounts[0]);
    } catch (error) {
      console.log(error);
    }
  };



  useEffect(() => {
    checkIfMetamaskIsInstalled();
    checkIfAccountChanged();
  }, []);

  return (
    <div className="mainContainer">
      {!currentAccount ? (
        <button className="waveButton" onClick={connectWallet}>
          Connect Wallet
        </button>
      ) : (
        <button className="waveButton" onClick={connectWallet}>
          {currentAccount}
        </button>
      )}
    </div>
  );
}

Main.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
)

This is simple connect to wallet application. Check if it works in your browser.

Link's here

6
  • thanks a lot!!! but ethereum.on('accountsChange') doesnt console.log anything.
    – Jerry
    Sep 21, 2022 at 10:02
  • You will have to write a statement to console it. Let me show you. And if it works, don't forget to accept the answer.
    – Ad-h0c
    Sep 21, 2022 at 10:03
  • dont worry i will accept the answer
    – Jerry
    Sep 21, 2022 at 10:05
  • I input your code. I dont know why my code doesnt work :( haaaaaaa
    – Jerry
    Sep 21, 2022 at 10:11
  • Look at my repl code. You might find where you are doing the mistake. [replit.com/@siva152000/waveportal-starter-project?v=1] (How to connect to metamask?) It is in src/app.jsx
    – Ad-h0c
    Sep 21, 2022 at 10:15
0

This is how I handle account change inside class component.

componentDidUpdate(prevProps) {
if (typeof window.ethereum !== 'undefined') {
    // detect Network account change
    window.ethereum.on('chainChanged', networkId => {
        console.log('chainChanged', networkId);
    });

    window.ethereum.on('accountsChanged', async(accounts) => {          
        //console.log('accountChanged', accounts);
        if(accounts.length > 0){
          // connected              
        } else {
          // not connected              
        }
    });

    window.ethereum.on('disconnect', (error) => {

    });
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.