I'm new to react but I'm facing a small issue. I'm building up a social platform for practice where user's are able to post, like and comment. I'm using Change stream and socket.io to detect any changes in my database.
Everything works perfectly fine but what I'd like to know is, that when I create a post I'd like the state that has been set to be sorted via date before mapping through the posts. knowing that when the useEffect is triggered the data retrieved would be sorted by date instead of scrolling all the way down to the new post created.
Here is my code snippet. I've tried different ways to sorting but unfortunately I'm unable to achieve it. I'd like the posts to be sorted by date when re-rendered to be displayed if that make sense.
const [posts, setPosts] = useState([]);
useEffect(() => {
const handler = (item) => {
setPosts((oldPosts) => [...oldPosts.filter(p => p._id !== item._id), item]);
};
socket.on('posts', handler);
return () => socket.off('posts', handler);
}, []);
posts
array because it's the newest one. I think there is no need to sort. Maybe I don't understand what you want exactly. – Nima Ebrazeh