How can I check if an account is already linked via Moralis.link()

When I switch accounts from my MetaMask I get to confirm whether the address is my account and connect it. However, on the second instance my function gets fired upon onAccountsChanged event, I get the following error:

image

Here is my onAccountsChanged event:

function monitorAccount(){
  Moralis.onAccountsChanged(async function (accounts) {
    const confirmed = confirm("Link this address to your account?");
    if (confirmed) {
      await Moralis.link(accounts[0]);
      document.getElementById("address").innerHTML = accounts[0];
      if(chainID == 137){
        updateTableBalances();
      } else {
        updateTableBalances(true);
      }
    }
    
    });
    
}

Really what I want is a smooth seamless experience where depending on the account switched to, I re-populate a table comprising on the user’s balances and show their current account address on the page (which is working thus far).

seems like your other wallet address is already registered as a user in the user table, you might wanna try to use a new address that hasn’t been authenticated yet?

Thanks for the response Yoseph, that’s not what I’m trying to figure out. It’s the part of how do I stop the same addresses from being linked (Moralis.link(accounts[0])) again? Is there a way for me to link them once and not do it again if they’ve already been linked?

Thanks

You could check with a cloud function if that address is already used, link should fail if that address was already linked. You could ask the user if he wants to link or authenticate with that address.

1 Like

Thanks for that, I’ve been learning a little more about cloud functions. I have a slight problem. I’m testing out in the API console but for some reason the result of my addresses are undefined. Would you know what I could be missing here:

I have three addresses inside the User table and I can get the whole address object with everything but when I try to only store the ethAddress in an array then I get this.

It’s all good I figured it out:

address.attributes.ethAddress
3 Likes