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);
}, []);
CodePudding user response:
Well actually we have two possibility:
1- updated item
is new. So put it at first index of array.
2- updated item
is duplicate. Then just update it's value using map.
const handler = (item) => {
setPosts((oldPosts) => {
const findItem = oldPosts.find((post) => post._id === item._id);
if (findItem) {
return oldPosts.map((post) => (post._id === item._id ? item : post));
} else {
return [item, ...oldPosts];
}
});
};
Be aware that in this method you should sort posts on the first render of the component by Date.
CodePudding user response:
All you need to is to run this code before setPosts and pass date sorted array to setPosts by using Following code.
yourArray.sort(function (a, b) {
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});