0

I am writing an amateur SPA, based on Vue (specifically the Quasar framework).

This application, in mounted(), connects to an MQTT broker to get some information (MQTT does not matter here - it could be an API called with fetch(), the point is that the results are available "after some time" in JS asynchronous way). This information is stored in this.results.

I use this.results in some components and the content is displayed as expected, and updated upon new results (i.e. a change in this.results) as expected as well.

Since this a front end for a home monitring program, I wanted to also display the last time the results were fetched and raise alerts if I did not get new results for some time (that would suggest that the monitoring backend itself crashed). I went for:

mounted() {
    // connect to the MQTT broker = new results will come. That could be a setInterval fetch()
    this.client = mqtt.connect("mqtt://mqtt.swtk.info:1884");
    this.client.on("connect", this.mqttConnect);
    this.client.on("message", this.mqttMessage);
    // check every 900 ms for the last time I got the results, and set a variable for the elapsed time
    setInterval(
      function() {
        console.log(this.results)
        this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
      },
      900
    )
  }

This is the message I continuously (every second) get on the console:

enter image description here

At the same time, this.results is defined: not only cntents from this.results are otherwise correctly displayed in components, but when looking at the DevTool Vue tab, I I see:

enter image description here

It looks like the this.result in the setInterval() function is assessed only once and is undefined - which is fine because it would not have been received at that time yet, but will shortly be set (upon getting the first results).

Shouldn't its value be used as it is "currently" in each of the 900 ms calls to the function?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 1
    Try `console.log(this)` instead and you will see the reason for the error. –  Dec 16 '20 at 11:30

1 Answers1

1

try to use arrow function () => {} like this

setInterval(
      () => {
        console.log(this.results)
        this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
      },
      900
    )
andrei040191
  • 408
  • 4
  • 7