0

I'm currently in the process of making a social media application. Right now I have a function that can post any content or text. I have a temporary data as well which is an array of objects, it already shows in the front page of my application. My problem now is whenever I post something it's showing at the bottom part of the app instead of at the top. I was thinking that since my array objects has an ID I can use the sort method so that my post is the one showing first instead of my temporary data. I just don't know how. Can anyone help?

Here's my code:

const Posts = () => {

    const initialPostData = [
        {
            id: 2,
            name: '',
            userId: 2,
            profilePic: '',
            desc: '',
            img: ''
        },
        {
            id: 3,
            name: '',
            userId: 3,
            profilePic: '',
            desc: '',
            img: ''
        }, 
    ];

    const [ content, setContent ] = useState(initialPostData);

    const addContent = ( post ) => {
        let newPost = {
            id: 1,
            name: 'Sleepy',
            userId: 1,
            profilePic: '',
            desc: post,
            img: ''
        }
        setContent([
            ...content,
            newPost
        ]);
    }

    return (
        <div className='posts'>
            <PostForm addPost={addContent}/>
            {content.map(post=>
            (<Post post={post} key={post.id}/>))}
        </div>
    )
};

export default Posts;

1 Answers1

2

If the only issue is that you want the new post to be at the top, you can just update your setContent statement to put the new item first:

setContent([newPost, ...content])

Or, if you do actually need to sort it by the id, you can do it like this:

return (
  <div className="posts">
    <PostForm addPost={addContent} />
    {content
      .sort((a, b) => a.id - b.id)
      .map((post) => (
        <Post post={post} key={post.id} />
      ))}
  </div>
);
asportnoy
  • 2,218
  • 2
  • 17
  • 31