简体   繁体   中英

How to show websocket data in front end?

I'm using a React Application that's it's connecting to a websocket in the following manner. And it's using React Hooks to store the stream of data. It looks like this:

React Hook:

const [socketStream, setSocketStream] = useState("");

WebSocket connection:

const token = getToken();

setSocketStream(Registering socket');

const socket = io(`API`, {
    query: { token },
    transports: ['websocket'],
})

  socket.on('connect', () => {
    setSocketStream("connected")
  })

  let time = 1

 socket.on('data', (body) => {
      socket.emit('confirm', body.time)
      const data = body.data
      const error = data.error
      setSocketStream(`\nResponse #${time} from socket. Message: ${data || error}`);
      time++
      if (error) {
          console.log(`\nError from socket: ${error}`)
          socket.close()
      }
      if(data === 'Finished build')
          socket.close()
  })
}, 3000)

What I wanna do is to show the stream of data inside my component. Something like:

<p>{socketStream}<p>

But the hook is not updating the values. Is there a way to do this?

Thanks in advance!

Assuming you are indeed getting data from the stream, you need to specify at what point in your component lifecycle it should update its state, that is

setSocketStream(Registering socket');

You will need to use useEffect() (functional way of implementing lifecycle method) hook to do this otherwise your component will keep rendering the initial empty string value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM