Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trouble with updating state with socket.io, after state is set it is not retained before the next socket message

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

The problem I see here is this

setComments([...comments, comment])

try to change it in

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading