0

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?

1
  • 1
    you have to use arrow functions in your set interval to have access to this (or bind to this). So: setInterval(() => { this is defined}) Moreover, you should clear your interval on destroy Commented Apr 29, 2020 at 22:27

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer and time Sturm. That works!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.