import { collection, query, where } from "firebase/firestore";
const citiesRef = collection(db, "cities");
const q = query(citiesRef, where("capital", "==", true));
import { query, orderBy, limit } from "firebase/firestore";
const q = query(citiesRef, orderBy("name"), limit(3));
我們來試著在題目中新增Unit(單元)欄位
參考上面的範例,我們把程式改為:
import { orderBy, query, where } from "firebase/firestore";
useEffect(() => {
async function fetchData() {
**const examCollection = collection(db, "English");**
**const queryExam = query(examCollection, where("unit", "==", 1));**
const querySnapshot = await **getDocs(queryExam);**
const temp = [];
querySnapshot.forEach((doc) => {
temp.push(doc.data());
console.log(`${doc.id} => ${doc.data().question}`);
});
setExams(() => [...temp]);
//set the first question and clean result here
setQuestion(temp[0].question);
setResult("");
}
fetchData();
// eslint-disable-next-line
}, []);
這樣就可以取得unit等於「1」的內容了
如果是要依據unit排序,把where()改成orderBy():
useEffect(() => {
async function fetchData() {
const examCollection = collection(db, "English");
const queryExam = query(examCollection, **orderBy("unit"));**
const querySnapshot = await getDocs(queryExam);
const temp = [];
querySnapshot.forEach((doc) => {
temp.push(doc.data());
console.log(`${doc.id} => ${doc.data().question}`);
});
setExams(() => [...temp]);
//set the first question and clean result here
setQuestion(temp[0].question);
setResult("");
}
fetchData();
// eslint-disable-next-line
}, []);
<aside> 💡 記得要import相關函數 (query, where, orderBy)
</aside>
假如我們把Exam.js改成
import "./styles.css";
import English from "./English";
import { useState } from "react";
export default function Exam() {
**const NUM_UNITS = 2;**
const [currentExam, setCurrentExam] = useState(0);
function onChangeExam(event) {
setCurrentExam(Number(event.target.value));
}
function next() {
if (currentExam < NUM**_UNITS**) {
setCurrentExam(currentExam + 1);
}
}
function getCurrentExam() {
return <English **unit={currentExam} next={next}** />;
}
return (
<div className="App">
<select name="exam" value={currentExam} onChange={onChangeExam}>
<option value={0}>**所有單元**</option>
<option value={1}>**單元1**</option>
<option value={2}>**單元2**</option>
</select>
{getCurrentExam()}
</div>
);
}
要如何在English.js收到Exam.js傳進來的變數? 可以利用props (請參考: React元件)