0

I have a comment section in my React app and I want to update it in real-time as other users comment. I use socket.io to listen to server sent events of new comments. When the app is notified about the new comment, I update the existing comments list with the new comment data.

However, when I'm trying to access comments state variable from the callback, it is always empty. How can I access comments from the callback so that I can append new data to the existing list of comments. Any help is highly appreciated.

const Discussion = ({ lessonId,lessonName }) => {
    const [comments, setComments] = useState([]);

    const updateComments = (data) => {
      // this is always empty, even though it contains a list of objects and rendered as comments
      console.log(comments) 
      // This results in something like [data]. Existing objects have been disappeared.
      setComments([...comments,data])
    }

    useEffect(() => {
      Axios.get('/courses/lessons/' + lessonId + '/comments')
        .then(res => {
           console.log(res.data);
           setComments(res.data);

           socket.on('reply',data => {
             console.log(data)
           })
           // existing list of comments is updated with new data.
           socket.on('comment_'+lessonId,(data) => updateComments(data))
           })
        .catch(err => {
            console.log(err);
            alert('An error occured');
        });
    }, [lessonId]);

    return <div></div>
};

1 Answer 1

2

updateComments is called inside useEffect and the comments values it uses will be limited to the closure of useEffect and hence it will not have access to the updated comments value unless useEffect has a dependency on comments

An optimized solution here is to make use of functional state updater

const updateComments = (data) => {
  setComments(prevComments => [...prevComments,data])
}
Sign up to request clarification or add additional context in comments.

Comments

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.