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>
};