'Vue data() is unavailable in events when using @microsoft/fetch-event-source for Server Sent Events
I'm trying to use fetchEventSource (from @microsoft/fetch-event-source) to process Server Sent Events for streaming data to the client. It works, in that the data is returned and I can log it to the console, but when I try to update my vue data in the onmessage event, I get the error:
TypeError: Cannot set properties of undefined (setting 'messages')
Any thoughts on the best way to get this working?
Basic test template:
<template>
<div>
<p>
<label>Message</label><br />
<textarea id="messages" v-model="messages"></textarea><br />
<button @click="getMessage">GET</button>
</p>
</div>
</template>
and the script:
import { fetchEventSource } from "@microsoft/fetch-event-source";
export default {
data() {
return {
messages: "",
};
},
mounted() {
this.messages = "initialized"; // this works
},
methods: {
getMessage() {
fetchEventSource("url-here", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
onmessage(msg) {
console.log("message", msg.data); // this works - data is here!
this.messages = msg.data; // this returns the error
},
});
},
},
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
