Skip to content
Advertisement

How do I order my database results from Firestore?

I am making an app that tracks the number of users’ tardiness using Firestore, but I can’t figure out how to order the list of results by number of tardy.

I’ve tried using the orderBy() function from Firebase docs, but I haven’t been able to implement it correctly with my existing code yet.

import { useState, useEffect } from 'react';
import './App.css';
import { db } from './firebase-config';
import {
  collection,
  getDocs,
  addDoc,
  doc,
} from 'firebase/firestore';

export default function App() {
  const [newName, setNewName] = useState('');
  const [newTardy, setNewTardy] = useState(0);

  const [users, setUsers] = useState([]);
  const usersCollectionRef = collection(db, 'users');

  const createUser = async () => {
    await addDoc(usersCollectionRef, {
      name: newName,
      tardy: Number(newTardy),
    }).then(() => {
      alert('User Created');
    });
  };

  useEffect(() => {
    const getUsers = async () => {
      const data = await getDocs(usersCollectionRef);
      setUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    };
    getUsers();
  }, []);

  return (
    <div className="App">
      <h1>Tardy List</h1>
      <input
        placeholder="Name..."
        onChange={(event) => {
          setNewName(event.target.value);
        }}
      />
      <input
        type="number"
        placeholder="Number of Tardies..."
        onChange={(event) => {
          setNewTardy(event.target.value);
        }}
      />
      <br />
      <button onClick={createUser}> Create User</button>

      {users.map((user) => {
        return (
          <div>
            <h2>Name: {user.name}</h2>
            <h2>Tardies: {user.tardy}</h2>
          </div>
        );
      })}
    </div>
  );
}

Advertisement

Answer

From reading the documentation on ordering data, something like this should do the trick:

const data = await getDocs(query(usersCollectionRef, orderBy("tardy")));
setUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
Advertisement