I just started with firebase and have problem with orderBy desc function when getting data

Viewed 33

In the function orderBy when passing the "desc" parameter, it does not return data, but when passing "asc" or blank, there is data.

const getListProduct = async () => {
    const products = await fs
      .collection("products")
      .orderBy("createAt", "desc") //problem is here.It just works orderBy("createAt", "asc") or orderBy("createAt")
      .startAfter(0)
      .limit(5)
      .get();
    let listProduct = [];

    for (let snap of products.docs) {
      let data = snap.data();
      data.ID = snap.id;
      listProduct.push({ id: snap.id, ...data });
      if (products.docs.length === listProduct.length) {
        
        setListData(listProduct);
      }
    }
  };
     
1 Answers

The value in startAfter() must be either a DocumentSnapshot or the value of field to start this query after. If createAt field is a Timestamp then it must be startAfter(<DATE_OBJ>) or snapshot of document from last query but you are passing a number. Try refactoring the code as shown below:

const products = await fs
  .collection("products")
  .orderBy("createAt", "desc")
  .startAfter(new Date(2022, 8, 17, 6, 54, 0)) // for testing Date(year, date, month, hh, mm, ss)
  .limit(5)
  .get();

This should return all products where startAfter is less than the provided timestamp in descending order.


Alternatively, you can store snapshot of the last query in your state and use it as shown below:
let lastSnapshot = null;

const q = fs.collection("products").orderBy("createAt", "desc")

if (lastSnapshot) {
  // Query has been executed before, use last snapshot
  q.startAfter(lastSnapshot);
}

const products = await q.limit(5).get();
Related