I want to display some sensors data from raspberry pi (using python socketio) in react as frontend and I am using nodejs as backend. Data is currently displaying in the console (nodejs) but I can't seem to figure out how it will displayed in react. Sorry for this basic question but I can't seem to find a reasonable way to implement this. Here are my codes for raspberry pi, node and react.
#raspberrypi code
import asyncio
import socketio
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('connection established')
@sio.event
async def message(data):
print('message received with ', data)
await sio.emit('fromAPI', {'msgFromPy': 'my response'})
@sio.event
async def disconnect():
print('disconnected from server')
async def main():
await sio.connect('http://localhost:5000')
await sio.wait()
if __name__ == '__main__':
asyncio.run(main())
Nodejs code
const io = require("socket.io")(5000);
io.on("connection", socket => {
// either with send()
console.log('Connected');
socket.send("Hello!");
// handle the event sent with socket.send()
socket.on("fromAPI", (data) => {
console.log(data);
socket.emit("fromAPI", data);
});
});
});
Following is react code
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:5000";
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("fromAPI", data => {
setResponse(data);
});
}, []);
return (
<p>
It's {response.msgFromPy}
</p>
);
}
export default App;
What should I do so that data from the node can be displayed in react. I am not getting any error in react as well. Thanks for helping