Search code examples
javascriptnode.jsvue.jsethereummetamask

Scope of Data in vue.js Module


I have the following code contained in my vue.js file/module:

 export default {
  name: 'App',
  data () {
    return {
      web3: null,
      account: null,
      contractInstance: null,
      userAccount: null
    }
  },
  mounted () {
    web3Cont().then((res) => {
      this.web3 = res
      this.contractInstance = new this.web3.eth.Contract(contractAbi, contractAddress)
      this.web3.eth.getAccounts().then((accounts) => {
        [this.account] = accounts
        console.log(accounts)
      }).catch((err) => {
        console.log(err, 'err!!')
      })
    })
    setInterval(function () {
      // Check if account has changed
      if (this.userAccount !== this.account) {
        this.account = this.userAccount
        this.updateInterface()
      }
    }, 1000)
  }
}

From my understanding, the variable exported in the data() function should all have a "global" scope within the file. However although I am assigning a value to the "account" variable in the web3Cont function, the value is still undefined when the setInterval function is executed.

What am I missing?


Solution

  • this now belongs to the function passed to setInterval.

    You have a couple options:

    function onInterval () {
      if (this.userAccount) {
      //
      }
    }
    
    setInterval(onInterval.bind(this), 1000);
    

    or

    setInterval(() => {
      if (this.userAccount) {
        //
      }
    }, 1000);
    

    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this for reference.

    In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).