1
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>
            {textData.map((text) => <li>{text}</li>)}
      </Container>
  ); 
}

export default Sock;

With help I have managed to display something on the UI but it currently only displays the array count and not the object inside the array. I am fairly new to React hooks any help or suggestions would be greatly appreciated.

2 Answers 2

4

There are few ways to take care of stale closure but for your simple case, you can use the functional update syntax to get the previous text data, and return a new instance of array (do not mutate existing state, using push).

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

Using the callback approach, you don't need to put textData in the useEffect's dependency array.

Sign up to request clarification or add additional context in comments.

3 Comments

It's good answer. But i would clarify Array.push returns a size of an array. So, author of question got it in his view.
The OP's intention was to use the text within the returned element {textData.map((text) => <li>{text}</li>)} thus I expected him to store list of texts in the state, not the count.
You're not understand. Your code works fine, but you didn't explain why OP got a number in his view. It's happen because Array.push returns a size of an array and OP try to render it in his component.
2

You have to join your data (text) with existing data (textData), try with:

setTextData([...textData, text]);

1 Comment

That's great, thanks a lot. I will set as the answer @moseRaguzzini

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.