3

If I register a meta mask event listener using:

provider.on('accountsChanged', accounts => {
  console.log('accounts:', accounts)
})

Is there a way to clean this listener? I'm use Vue.js which means if the listener is registered upon loading of the component it's gonna register a new listener every time the component is loaded. I could use a custom workaround, checking if the listener has already been registered but maybe there's a proper way to do this that I haven't found in the metamask documentation yet. Thanks for the help!

1 Answer 1

6

Struggled a bit with this myself since it is not very well documented. This is what worked for me in the end:

provider.on("accountsChanged", handleAccountsChanged)

function handleAccountsChanged() {
  // do something
}

// When leaving the page (Vue 3 - Composition API)
onUnmounted(() => {
  if (provider.removeListener) {
    provider.removeListener("accountsChanged", handleAccountsChanged)
  }
})

Hope that helps anyone.

Your Answer

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

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