Jose Peres
Jose Peres

Reputation: 317

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!

Upvotes: 1

Views: 313

Answers (1)

Niyi Aromokeye
Niyi Aromokeye

Reputation: 450

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.

Upvotes: 1

Related Questions