Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks & UseEffect not updating display with socketIO data

import React, {useState, useEffect} from 'react';
import socketIO from 'socket.io-client';
import Container from 'react-bootstrap/Container';

function Sock() {
   const [textData, setTextData] = useState([]);

   useEffect(() => {
      const socket = socketIO('http://127.0.0.1:5009');
      socket.on('chat message', (text)  =>  {
         setTextData([
             textData.push(text)
          ]);
      console.log(textData);
      });
   },[]);

  return (
     <Container>
        <h1>Socket</h1>
        <li>{textData}</li>
     </Container>
  ); 
}

export default Sock;

The initial return does an initial render and displays everything. but then does not re render when incoming data from the socket. It console logs everything fine.

I am fairly new to hooks, I have already achieved this doing it the class way but am currently refactoring the app to use hooks instead. Any suggestions would be greatly appreciated.

like image 772
david michael Avatar asked Aug 13 '26 05:08

david michael


1 Answers

React doesn't understand that textData changed because you don't change reference on array. You can try this:

import React, {useState, useEffect} from 'react';
import socketIO from 'socket.io-client';
import Container from 'react-bootstrap/Container';

function Sock() {
   const [textData, setTextData] = useState([]);

   useEffect(() => {
      const socket = socketIO('http://127.0.0.1:5009');
      socket.on('chat message', (text)  =>  {
         setTextData([
             ...textData,
             ...text,
         ]);
         console.log(textData);
      });
   },[textData]);

  return (
     <Container>
        <h1>Socket</h1>
        {textData.map((text) => <li>{text}</li>)}
     </Container>
  ); 
}

export default Sock;

But why do you want to set handler on socket every time your textData will change? So, i think you should not pass [textData] to useEffect.

like image 81
svltmccc Avatar answered Aug 14 '26 18:08

svltmccc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!