Skip to content Skip to sidebar Skip to footer

React Hooks & Useeffect Not Updating Display With Socketio Data. Only Renders Elements In Array

import React, {useState, useEffect} from 'react'; import socketIO from 'socket.io-client'; import Container from 'react-bootstrap/Container'; function Sock() { const [textData

Solution 1:

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.

Solution 2:

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

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

Post a Comment for "React Hooks & Useeffect Not Updating Display With Socketio Data. Only Renders Elements In Array"