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.
JavaScript
x
65
65
1
import { useState, useEffect } from 'react';
2
import './App.css';
3
import { db } from './firebase-config';
4
import {
5
collection,
6
getDocs,
7
addDoc,
8
doc,
9
} from 'firebase/firestore';
10
11
export default function App() {
12
const [newName, setNewName] = useState('');
13
const [newTardy, setNewTardy] = useState(0);
14
15
const [users, setUsers] = useState([]);
16
const usersCollectionRef = collection(db, 'users');
17
18
const createUser = async () => {
19
await addDoc(usersCollectionRef, {
20
name: newName,
21
tardy: Number(newTardy),
22
}).then(() => {
23
alert('User Created');
24
});
25
};
26
27
useEffect(() => {
28
const getUsers = async () => {
29
const data = await getDocs(usersCollectionRef);
30
setUsers(data.docs.map((doc) => ({ doc.data(), id: doc.id })));
31
};
32
getUsers();
33
}, []);
34
35
return (
36
<div className="App">
37
<h1>Tardy List</h1>
38
<input
39
placeholder="Name..."
40
onChange={(event) => {
41
setNewName(event.target.value);
42
}}
43
/>
44
<input
45
type="number"
46
placeholder="Number of Tardies..."
47
onChange={(event) => {
48
setNewTardy(event.target.value);
49
}}
50
/>
51
<br />
52
<button onClick={createUser}> Create User</button>
53
54
{users.map((user) => {
55
return (
56
<div>
57
<h2>Name: {user.name}</h2>
58
<h2>Tardies: {user.tardy}</h2>
59
</div>
60
);
61
})}
62
</div>
63
);
64
}
65
Advertisement
Answer
From reading the documentation on ordering data, something like this should do the trick:
JavaScript
1
3
1
const data = await getDocs(query(usersCollectionRef, orderBy("tardy")));
2
setUsers(data.docs.map((doc) => ({ doc.data(), id: doc.id })));
3