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.

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.