Home > Software engineering >  How to sort firebase document by date in React?
How to sort firebase document by date in React?

Time:05-12

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

CodePudding user response:

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);

CodePudding user response:

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.

  • Related