'Fetching data from websocket to react
I'm relatively new to React, and am looking to combine my React application with a websocket connection.
I'm able to establish a connection via the websocket connection, but am unable to display in my app.
backend code is
#!/usr/bin/env python
import asyncio
import random
import datetime
import websockets
import json
async def handler(websocket, path):
while True:
data = [
{
"name": "Random Int 1",
"number": random.randint(0, 3000),
"category": "Pun"
}
]
await websocket.send(json.dumps(data))
await asyncio.sleep(1)
start_server = websockets.serve(handler, "127.0.0.1", 8888)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
the react code is
import { useState, useEffect } from "react";
export default function App() {
const [number, setNumber] = useState("");
useEffect(() => {
const ws = new WebSocket("ws://127.0.0.1:8888/");
ws.onopen = () => {
console.log("Connection Established!");};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
setNumber({data.number});};
ws.onclose = () => {
console.log("Connection Closed!");};
ws.onerror = () => {
console.log("WS Error");};
return () => {
ws.close();
};
}, []);
return (<div>
<p>number :{person.number}</p>
</div>
);
}
Solution 1:[1]
A couple of minor errors in your code:
Update your setNumber()
to:
setNumber(data.number);
and person.number
doesn't exist (as the variable is just number
, so:
<p>number: {number}</p>
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 | John Detlefs |