skip to Main Content

I’m having an issue dealing with a stream of messages being emitted in my socket.io client in my React app. On the backend, I have an express server that takes a stream from the twitter api and for each message in the stream, I emit a message through the socket.io server.

On the clientside, I use a useEffect hook to instantiate the socketio client and then I turn the socket on and when I get the new event I concatenate the state of the component with the new event.

The issue I’m having is that the state is constantly being overwritten with the newest event only, instead of an array of all the events received so far. When I mutate the state using pushing instead of concatenating to the array I can see the array grow, so I think the issue is that the state that I concatenate to is the original state from before I start receiving events. I’m not sure how I can handle this without mutating the state which I know is a bad practice. Below is some of the code involved:

const TestComponent = props => {
  const [testList, setTestList] = useState([]);

  useEffect(() => {
      const socket = socketIOClient(ENDPOINT);

      socket.on("newData", data => {
        const updatedList = testList.concat(data.newData);

        setTestList(updatedList);
      });
  }, []);

2

Answers


  1. It looks like you forgot to add testList in dependencies array:

    useEffect(() => {
         // ...
    }, [testList]);
    

    Don’t forget to clear your subscription.

    Login or Signup to reply.
  2. If you want to push your new data into an existing array of your state :

    const TestComponent = props => {
      const [testList, setTestList] = useState([]);
    
      useEffect(() => {
        const socket = socketIOClient(ENDPOINT);
    
        socket.on("newData", data => {
          setTestList([
            ...testList,
            data.newData
          ]);
        });
      }, []);
    };
    

    By using […arr, item], you create a new array, add all the elements from arr, and push an item into the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search