2

i'm creating each document as:

  const postCollection = collection(database, "posts");

  const submitPost = async () => {
    await addDoc(postCollection, {
      title,
      body,
      comments: [{ userId: "", content: "", name: "" }],
      likes: { count: 0, users: [] },
      date: new Date().toLocaleDateString(),
      user: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
    });
  };

And then i'm retrieving each document as:

  const postCollection = collection(database, "posts");

  const getPost = async () => {
    const data = await getDocs(postCollection);
    const newData = data.docs.map((doc) => ({
      ...doc.data(),
      id: doc.id,
    }));
    setPostList(newData);
  };

But how can i sort them by date? From last to first. Thanks in advance

4
  • You need to use query() with where() functions. And you need to create a field in each document with Firebase Timestamp. Commented May 11, 2022 at 20:30
  • I read the documentation, but i didn't understand it fully, so i came here to ask, because i thought that here was the place to do that. Commented May 11, 2022 at 21:42
  • Well, "stack overflow" is a programming issue you may encounter in a future. You should be trying to solve issues by your self, and ask questions if you are not able to solve them by your self. Commented May 11, 2022 at 22:06
  • My advice is to read firebase documentation 2-3x with trying to understand it. Then practice by coding and if you don't remember what you need to use you will know how and where to find it in documentation. Commented May 11, 2022 at 22:13

2 Answers 2

3

Firestore has a method called orderBy. You can use it to order the documents in descending order. See sample code below:

const postCollection = collection(database, "posts");

const getPost = async () => {
    const data = await getDocs(query(postCollection, orderBy('date', 'desc')));
    const newData = data.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
    }));
    
   setPostList(newData);
};

For more information, you may check Order and limit data with Cloud Firestore.

Sign up to request clarification or add additional context in comments.

Comments

1

You can change your get like this

const getPost = async () => {
    const data = await getDocs(postCollection);
    const docs = data?.docs
    const sortedData = docs?.sort((a,b)=> a.date - b.date);
    const newData = sortedData.map((doc) => ({
      ...doc.data(),
      id: doc.id,
    }));
    setPostList(newData);
  };

Here also basic working logic but that's same anyway

let docs = [{date: 1}, {date: 5}, {date: 2}]
const test = docs?.sort((a,b)=> a.date - b.date);
console.log(test);

2 Comments

Thank you. But, i'm adding the date as new Date().toLocaleDateString(), and it returns to me like 11/05/2022, so every post would basically have the same date right? So in order to sort it correctly i would have to add minutes too?
You can sort it with new Date().getTime() functions but probably you will need a bit work around. I would save in post as milliseconds then you can convert it to toLocaleDateString when you show this date in frontend @JoséCarlos

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.