Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
        },
      });
    },
  },
};

>Solution :

You can try with arrow function or like :

getMessage() {
  const self = this
  fetchEventSource("url-here", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    onmessage(msg) {
      console.log("message", msg.data); // this works - data is here!
      self.messages = msg.data; // this returns the error
    },
  });
},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading