Skip to content
Advertisement

Variable declared in data() is Undefined in Listener

I am declaring a “userid” variable in the data() section of my component. Within a mounted() method, I am initiating a listener for MetaMask. Upon changing account in MetaMask this listener is triggered. However, the “userid” (declared in data()) within the listener is undefined.

 export default {
  name: 'App',
  data () {
   return {
    userid: null
   }
 },
 mounted () {
 ...
 // MetaMask Listener
 window.ethereum.on('accountsChanged', function (accounts) {
  this.userid = accounts
 })
}

How can I solve this problem?

Advertisement

Answer

Vue runs in strict mode. That means that this is binded to regular function itself.

You have 3 ways to solve this problem:

Use arrow function:

 window.ethereum.on('accountsChanged', accounts => {
  this.userid = accounts
 })

Use .bind()

 window.ethereum.on('accountsChanged', function (accounts) {
  this.userid = accounts
 }.bind(this))

Declare a variable outside and assign this to it:

 var self = this;
 window.ethereum.on('accountsChanged', function (accounts) {
  self.userid = accounts
 })
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement