Skip to content
Advertisement

Receive data continuously from socket react

I’m currently using this code for receiving data from sockets Code:

 socket.on('send_image', (message) => {
        setImage(message.image)
        console.log(message)
      })

the server sends data(images from camera) continuously. how to receive it without refreshing? i tried one method that requests data every milliseconds. i don’t know whether it is a good way or not

Request every milliseconds code:

 useEffect(() => {
    const id = setInterval(() => {

      socket.on('send_image', (message) => {
        setImage(message.image)
        console.log(message)
      })
      
    }, 10);
    return () => clearInterval(id);
  }, []); 

is there any other way to continuously receive data from sockets?

Advertisement

Answer

To update the local state as soon as a send_image message is received, just register the handler in your useEffect.

useEffect(() => {
  const handler = (message) => {
    setImage(message.image);
    console.log(message);
  };
  socket.on("send_image", handler);
  return () => socket.off("send_image", handler); // assuming `.off` deregisters a callback
}, []);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement