2

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>
);
}

1 Answer 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>
Sign up to request clarification or add additional context in comments.

2 Comments

I followed your suggestion, still not able to see the value on the browser, what else i can try
it say undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.