Get current account address when switching wallets?

how do I use moralis to do this?

   const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    const account = accounts[0];

When I connect a user, the ethAddress stays the same even when a user changes his metamask account, should I directly call metamask or is there a way to get the current account through moralis?

Hi, what I do is that I create use the useState hook to save accounts logged in with moralis. Then I use the useEffect hook with the accounts dependency so that everytime accounts change you can do whatever you want in the useEffect (so display the other account).

1 Like

what do you mean? when the user switches account (different wallet address) the moralis “user” object doesn’t change, best I can do is using “onAccountChanged” but than I either link the user with moralis which doesn’t work nicely for some reason? the user is connected based on metamask but moralis asks for signature again…

      await Moralis.link(newAddress, {
                wait: false,
                silent: true
              })

I would like to do this without asking for a new signature, since the user already logged in to moralis, so him changing wallet should not be an issue if I link it no? like, what’s the point of asking a signature again?

A Moralis user is not same thing as switching an account in MetaMask. When the user signs the message it’s sent to Moralis for verification and moralis sets up a User in your database if the signature is correct.

1 Like

sorry I meant using the account object from useMoralis() hook
for instance:


    const {isAuthenticated, Moralis, account} = useMoralis();

const getData = async () => {
        if(account){
            setIsLoading(true);
            try{
            let data = getUserData();
            }
            catch (error) {
            setErrorMessage(error.toString());
            setIsLoading(false);
        
        }}
        else{
            setErrorMessage('you must be logged in');
        }
    }
    useEffect(() => {
        getData();
    }, [account])

If there are mutliple accounts connected each time you disconnect an account from metamask the account const will change so useEffect hook will be called.