简体   繁体   中英

Using Firebase order by the newest items first

So, I'm new with Firebase, and I'm trying to fetch the items from Database, the problem is that they come unsorted, some newest posts show at the bottom some show at the top, what I want to do is sort them from the newest to the oldest so I can list them like that.

Here is my firebase code:

const GetItems = async (setItems, setLoading, target) => {
  setLoading(true);
  const itemsCollectionRef = collection(db, target);

  const data = await getDocs(itemsCollectionRef);
  setItems(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
  setLoading(false);
};

So this code works perfectly, but it gives me the unsorted list.

You can use the orderBy method to sort the data.

const itemsCollectionRef = collection(db, target).orderBy('date', 'desc');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM