'React doesn't accept event stream from flask
So I'm trying to send data from flask to react on every hour for example, since this is a server push thing I decided to go with Event stream push from backend. Server is pushing as it should, but on React side I always get an error
This is backend code:
@app.route("/stream/<int:uid>", methods=["POST", "GET"])
def stream(uid):
# if not uid:
# # todo not implemented
# # 503 - Service Unavailable - server is not ready to handle the req
# return {"msg": "UID not provided"}, 503
def eventStream():
print(f"connected uid: {uid}")
while True:
if config.updated_flag == 1:
data = Investment.get_all_by_user_id(uid)
print(f"yielding new data now | time: {datetime.now()}")
config.updated_flag = 0
yield f"data: {data}\n\n"
return Response(eventStream(), mimetype='application/event-stream')
This is the frontend where I'm accepting the eventStream:
useEffect(() => {
const sse = new EventSource(`${serverBaseURL}/stream/${props.userId}`, );
sse.onmessage = e => {
console.log(e.data)
}
sse.onerror = (err) => {
// error log here
console.log("error");
console.log(err)
sse.close();
}
return () => {
sse.close();
};
}, []);
On the first push that server does, this is the error that I get:
After this error, server is still yielding data, but there is nothing happening on the client
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

