'Javascript EventSource get stuck on pending state
I am using Server-Sent Events and the Javascript EventSource API for a live React dashboard, and I have multiple tabs, each of which uses one EventSource. When I navigate between different tabs the stream of events gets stuck on pending like the last "live" stream on the screenshot below:

Because of this the data is not loaded into the React dashboard and is stuck on loading. I can see that the streams that are opened earlier despite the fact that I close them:
const [data, setData] = useState(undefined);
const reportDataEventSource = new EventSource(
"http://localhost:8080/report/heatMap/live"
);
useEffect(() => {
reportDataEventSource.onmessage = e => {
setData(JSON.parse(e.data));
};
return () => reportDataEventSource.close()
}, []);
What can be the reason for this and how can I fix this?
Solution 1:[1]
"http://localhost:8080" indicates that you are using webpack-dev-server and since you did not set withCredentials:true in eventSource, that means you are allowing "*" wildcard for CORS but you have to set up CORS policy in webpack.config.js
devServer: {
historyApiFallback: true,
watchOptions: { aggregateTimeout: 300, poll: 1000 },
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
},
If this does not resolve the issue, set onError and log the error:
useEffect(() => {
// this also should be inside useEffect
reportDataEventSource.onmessage = e => {
setData(JSON.parse(e.data));
};
reportDataEventSource.onerror = () => {
// error log here
reportDataEventSource.close();
}
return () => reportDataEventSource.close()
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yilmaz |
