Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Variable outside await fetchEventSource is undefined #77

Open
ducknificient opened this issue Mar 3, 2024 · 2 comments
Open

Variable outside await fetchEventSource is undefined #77

ducknificient opened this issue Mar 3, 2024 · 2 comments

Comments

@ducknificient
Copy link

The code is working as expected

onmessage(ev) {
       console.log(ev.data);
}

However, when using the ev.data , i can't access variable outside fetchEventSource. How to handle it ?

@rcardona-eb
Copy link

The problem right there @ducknificient is that the closure doesn't know about the variables outside fetchEventSource methods. I handled that issue by using var variables declared somewhere else outside fetchEventSource call. Those variables will be available on the global scope and then you'll be able to use them inside those events. Binding the method call didn't work for me.

@Nokic233
Copy link

import { fetchEventSource } from '@microsoft/fetch-event-source';

const arr = [1, 2, 3];

async function handle(callback) {
    await fetchEventSource('/api/sse', {
        onmessage(ev) {
            callback(ev);
        },
    });
}

handle(ev => {
    //  access variable outside
    arr.push(ev.data);
});

I don't know if my code is what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants