Issue
I am trying to subscribe to an API call using SSE,
addAsArray(message){
array.push(message)
}
calling of SSE:
let src = fetchEventSource('api link', {
method: 'POST',
...
async onmessage(e){
if(e.text.includes('[END]')){
this.addAsArray(e.text)
}
}
However, I am getting this error:
TypeError: Cannot read properties of undefined (reading 'addAsArray')
I understood that async functions may require await
, hence I tried doing this
async addAsArray(message){
array.push(message)
}
calling of SSE:
let src = fetchEventSource('api link', {
method: 'POST',
...
async onmessage(e){
if(e.text.includes('[END]')){
await this.addAsArray(e.text)
}
}
However, I am still getting the same error. What did I do wrong here?
Solution
In your case, it seems like this inside the onmessage function is undefined. This is because the onmessage function creates its own context, and this inside that function does not refer to the outer scope.
One way to solve this issue is to use an arrow function for onmessage, which does not have its own this and will inherit this from the parent scope. Here’s how you can modify your code:
let src = fetchEventSource('api link', {
method: 'POST',
...
onmessage: async (e) => {
if(e.text.includes('[END]')){
this.addAsArray(e.text)
}
}
});
Answered By - Den
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.