[SOLVED] How to prevent Moralis.onAccountChanged to run if the account is saved already?

How can I modify the following code so that the alert fired once?

Moralis.onAccountChanged( async (account) => {
const confirmed = confirm("Link this account?");

if (confirmed) {
await Moralis.link(account);
let user = Moralis.User.current();
console.log("new account ethAddress: ", user.get("ethAddress"));
}
});

Thanks in advance.

Store this function in a constant data type and call the function when you want to cancel the event listening.

const cancleEvent = Moralis.onAccountChanged( async (account) => {
const confirmed = confirm("Link this account?");

if (confirmed) {
await Moralis.link(account);
let user = Moralis.User.current();
console.log("new account ethAddress: ", user.get("ethAddress"));
}
});

// call the cancleEvent to cancel 
cancleEvent()

How can I tell if the Account is already saved in Moralis db?
I want to cancel the function only when the account is already in the Moralis db.
Or am I missing something?

Thanks!

you can add a if condition inside the Moralis.onAccountChanged to check if the user is already linked by querying the user class database, and run the account link logic only if the account address is not found in the database or else you can exit the function.

Thanks @johnversus,
Is this done by Cloud Functions?
If you can show some example code, that would be greatful.

You can query from your app. This code returns the array of addresses of the logged-in user.

const query = new Moralis.Query("_User")
query.find().then((data) => {console.log(data[0].get("accounts"))})
2 Likes

Thanks! Great. I try this out.

This is what I configured on bubble. It works great! Thanks again.

const query = new Moralis.Query("_User")
query.find().then((data) => {

const queryUser = data[0].get("accounts");
console.log("queryUser:", queryUser)

const  containsEth = (queryUser.indexOf(ethAddress ) > -1);

if(!containsEth) {
// Save new Metamask account to Moralis db
Moralis.onAccountChanged( async (account) => {

await bubble_fn_onAccountChanged(JSON.stringify(account));

});
}

})

1 Like