Home > Software design >  Trouble with updating state with socket.io, after state is set it is not retained before the next so
Trouble with updating state with socket.io, after state is set it is not retained before the next so

Time:04-06

So I am trying to make a basic comment app using reactjs, I have a nestjs backend which I know already works as I made a bare bones html page to test the concept.

Basically on a new "message" I am trying to set the state of comments equal to [...comments, newComment] so it retains the previous comments.

But what is happening is every time I receive a message from the server, my state (comments) is getting overwritten with the new message and is not retaining any data.

I did some trouble shooting and it looks like the state (comments) is not being set at all? Here is my code:

const socket = io('http://localhost:4000');

function App() {

    const [comments, setComments] = useState([
    ]);

    function newComment(comment) {
        console.log("Request for new comment: ");
        console.log(comments);
        setComments([...comments, comment]);
    }

    useEffect(() => {
        console.log("Comments updated to: ")
        console.log(comments);
    }, [comments]);

    useEffect(() => {
        socket.on("message", data => {
            const theComment = data.data;
            let leComment = { id: 4, name: 'ted', comment: theComment }
            newComment(leComment);
        });
    }, []);

Here is my console in chrome for debugging: Console

Any help or suggestions is much appreciated, I've been stuck on this for a whole day now!

The end result I'm looking for is just for any new "message" that comes in, the comment in that message is appended to my state which is called comments

CodePudding user response:

The problem I see here is this

setComments([...comments, comment])

try to change it in

setComments(comments => [...comments, comment])

  • Related