Luka Miljković
Luka Miljković

Reputation: 126

Sorting Firebase data

I'm making a simple todo app with ReactJS and Firebase and I want to sort my todos by the time they were made. I get that I need to use server timestamps, but can't figure out a way to implement sorting to my way of displaying Firebase data. This is how I fetch the data:

useEffect(() => {
      const getTodos = async() => {
        const data = await getDocs(todosRef);
        setNewTodos(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
      }
      getTodos();
    }, [])

And this how I add new todos to the database:

await addDoc(todosRef, {
      text: input,
      dueDate: date,
      comments: [],
      //timestamp: firebase.firestore.FieldValue.serverTimestamp()
    });
    setInput('');
    window.location.reload();
  }

Plus, when I try to add the new todo with the timestamp nothing happends. It won't push it to the database, so that's why it's commented out.

Upvotes: 1

Views: 309

Answers (1)

Min
Min

Reputation: 528

For serverTimestamp you can just directly import it in modular v9.

import { addDoc, serverTimestamp } from "firebase/firestore";

await addDoc(todosRef, {
    timestamp: serverTimestamp()
 })

As for timestamp sorting you can simply generate a query and order by timestamp descending.

const q = query(todosRef, orderBy("timestamp", "desc");
const data = await getDocs(q);

Upvotes: 1

Related Questions