0

I've got a little bit problem with sorting posts by the time of adding a post in React and Firebase. I think the easiest solution is to add a timestamp property but I don't want to do it. Is it any other way to do this?

import { useEffect, useState } from 'react';
import './Post.css';
import Post from './Post';
import Profile from './Profile';
import db from './firebase';

const Content = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        db.collection('posts').onSnapshot(snapshot => (
            setPosts(snapshot.docs.map(doc => doc.data()))
        ))

    }, [])

   return (
   <div className="feed">
    <div className="feed__header">
        <h2>Home</h2>
    </div>
    <Profile />
    {posts.map(post => (
        <Post
            key={post.text}
            name={post.name}
            surname={post.surname}
            text={post.text}
        />
    ))}

   </div>
   )
  }
export default Content;

If something is unclear feel free to ask :)

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
Stairss
  • 157
  • 1
  • 8
  • Where do you attempt to [sort your array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)? On what property are you trying to sort it? – David Apr 11 '21 at 21:31
  • @David Thanks for the response, I edited my snippet to be more accurate. – Stairss Apr 11 '21 at 21:41
  • Can you clarify the problem though? It sounds like you just want to sort an array of objects in JavaScript, which is well documented and has many examples available and I see no attempt to do so in the code. You could sort the array when setting the state, or when displaying it in the render. What exactly isn't working as expected? – David Apr 11 '21 at 21:43
  • Sure, at the beginning I made `new Date()` object and done everything like was in this post: 'https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property', but I want to know if is it an easier way to do it :) – Stairss Apr 11 '21 at 21:47
  • *"at the beginning I made new Date() object"* - What exactly do you mean by that? The code shown has no new `Date` object. Nor do I see how creating one in this context would help you sort the array. Take a look at the link in my first comment above, that's the JavaScript `sort` function for an array. If you want to sort an array, that's really the place to start. – David Apr 11 '21 at 21:50

0 Answers0