I am currently working on a beginner level single-page application (SPA) using Vue, specifically the Quasar framework.
In this application, during the mounted()
lifecycle hook, it connects to an MQTT broker to retrieve some information. This information is stored in this.results
, which becomes available asynchronously after some time.
I utilize the data from this.results
in various components for display and ensure that it updates accordingly when new results are received.
Since this SPA serves as a frontend for a home monitoring system, I also wanted to include the timestamp of the last data retrieval and trigger alerts if no new results are obtained within a certain timeframe, indicating a possible backend failure. To implement this, I added the following code snippet:
mounted() {
// Connect to the MQTT broker to receive new results. Alternatively, use setInterval with fetch()
this.client = mqtt.connect("mqtt://mqtt.swtk.info:1884");
this.client.on("connect", this.mqttConnect);
this.client.on("message", this.mqttMessage);
// Check every 900ms for the time elapsed since the last data retrieval and update the variable accordingly
setInterval(
function() {
console.log(this.results)
this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
},
900
)
}
Continuously, I see this message being logged in the console:
https://i.sstatic.net/AvkEQ.png
Simultaneously, even though this.results
is indeed defined and its contents are correctly displayed in components, when inspecting the DevTool Vue tab, I notice:
https://i.sstatic.net/ZePQJ.png
It seems like within the setInterval()
function, the value of this.result
is evaluated only once and is initially set to undefined
, which is expected since the data might not have been received at that point but will be updated shortly afterwards.
Shouldn't the current value of this.result
be used in each call of the function within the 900ms interval?