2 years ago

#47146

test-img

V. Velibor

React cant read data send from server through SocketIO

So I have Flask REST API and React frontend.

I'm trying to send a simple string from flask to react every 20 seconds using sockets.

Based on documentation of Flask-SocketIO, this is how you built a function to emit something that originates on the backend, I built a function which emits some dumb data for now:

def send_updates():
    socketio.emit("newdata", {'msg': str(datetime.now())}, namespace='/home')
    # print("i am executed now " + str(datetime.now()))

I run this function every 20 seconds:

scheduler = BackgroundScheduler()
scheduler.add_job(  func=send_updates, 
                    trigger='interval', 
                    seconds=20)
scheduler.start()

In the console on the backend I can see that the function is emitted but on the frontend nothing is printed. Frontend (React.js)

    useEffect(() => {
        let socket = io.connect("http://localhost:5000/home")
        socket.addEventListener("newdata", inc_data => {
            console.log("hit")
            console.log(inc_data)
        })
        return () => {
            socket.disconnect()
        }
    }, [])

Besides all of that I have connect and disconnect functions on the backend:

@socketio.on("connect", namespace="/home")
def frontend_connection():
    print("Client is Connected")
    # socketio.emit("connect", {"hello": "world"})

@socketio.on("disconnect", namespace="/home")
def frontend_disconnection():
    print("Client is Disconnected")

On the server side I can see that socket connection is established, but on the client side, nothing is ever printed in the console. I tried socket.on insted of addEventListener but the situation is the same. Also both connecting and disconnecting to the server print messages into the server console.

Server ouput

What is the right way to do this? Am I using useEffect the right way? where should I connect to the socket in react app?

If someone has time and will to help me the whole problem would be: I have an external API from which I get updated data every hour. Each time I get new values from external API I should do some transformations and send transformed data to the client via web sockets.

This is the full problem, but my goal for now is to just send simple string on interval from flask to react using sockets

python

reactjs

flask

socket.io

flask-socketio

0 Answers

Your Answer

Accepted video resources