[英]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.我正在制作一个使用 Firestore 跟踪用户迟到数量的应用程序,但我不知道如何按迟到数对结果列表进行排序。
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.我已经尝试使用 Firebase 文档中的orderBy() function ,但是我还不能用我现有的代码正确实现它。
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>
);
}
From reading the documentation on ordering data , something like this should do the trick:通过阅读有关ordering data的文档,这样的事情应该可以解决问题:
const data = await getDocs(query(usersCollectionRef, orderBy("tardy")));
setUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.