coldasspirit
coldasspirit

Reputation: 127

how can i sort firebase timestamp data reverse reactjs

When I create new note, it orders old to new, but I want to order new to old (reverse it). How can i do this ?

my codes:

const notesRef = useFirestore().collection('users').doc(uid).collection("notes");
  const {status, data} = useFirestoreCollection(notesRef.orderBy("timezone"));

and its image: (Here, it order like 1-2-3, but i want to order, 3-2-1, new to old) enter image description here

our return like map:

 {data?.docs?.map((d, index) => {
              return (<Note
                      key={index}
                      id={index}
                      title={d.data().title}
                      content={d.data().content}
                      onDelete={deleteNote}
                      onDocId={d.id}
                      timezone={d.data().timezone}
                    />);
            })}

Upvotes: 1

Views: 781

Answers (2)

Himanshu Gupta
Himanshu Gupta

Reputation: 305

There are a bunch of ways of doing this.

  • Fetch the data in reversed order from firebase. I am using 25 as an example. You can choose the limit as per your requirements.
notesRef.orderBy("timezone").limitToLast(25);
  • Reverse the data on the client-side
const {status, data} = useFirestoreCollection(notesRef.orderBy("timezone"));
console.log(data.docs.reverse())

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

To sort a query in descending order, you can pass a second parameter to orderBy. So:

notesRef.orderBy("timezone", "desc")

Also see the Firebase documentation on ordering data.

Upvotes: 1

Related Questions