再會,
請幫我弄清楚如何過濾firestore查詢以僅顯示今天的資料。
這是我的反應代碼:
`
const History = () => {
const [codeexplainer, setExamples] = useState([]);
const [user] = useAuthState(auth);
const uid = user ? user.uid : "null";
useEffect(() => {
const fetchData = async () => {
const response = await fetch("/api/code/firebase-config");
const data = await response.json();
setExamples(data);
};
fetchData();
}, []);
const filteredData = useMemo(() => {
if (uid) {
return codeexplainer
.filter((result) => result.uid === uid && result !== undefined)
.sort((a, b) => b.timestamp - a.timestamp)
// .slice(0, 10);
}
return undefined;
}, [codeexplainer, uid])
const datafromfirebase = useMemo(() => {
if (filteredData && filteredData.length > 0) {
return filteredData.map((result) => (
<>
<Examples
code={result.code}
result={result.explanation}
/>
</>
))
} else {
return <p>Hey there! Add some code snippets and come back to see your history here.</p>
}
}, [filteredData])
`
示例 Firestore 資料

這是我目前使用的 Firebase 配置。
Firebase 配置:
import { initializeApp } from "firebase/app";
import { getFirestore } from "@firebase/firestore";
import {
collection,
addDoc,
getDocs,
serverTimestamp,
} from "firebase/firestore";
export const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
const resultsCollectionRef = collection(db, "codeexplainer");
const profaneCollectionRef = collection(db, "swear");
export default async function firebaseGet(req, res) {
if (req.method === "GET") {
const data = await getDocs(resultsCollectionRef);
const response = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
res.status(200).json(response);
}
}
export async function createFirebaseData(code, user, choices, userid) {
await addDoc(resultsCollectionRef, {
code: code,
user: user,
explanation: choices,
timestamp: serverTimestamp(),
uid: userid,
});
}
export async function getFirebaseData(req, res) {
const data = await getDocs(resultsCollectionRef);
const response = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
return response;
}
export async function loggedProfane(code, user, userid) {
await addDoc(profaneCollectionRef, {
code: code,
timestamp: serverTimestamp(),
user: user,
uid: userid,
});
}
謝謝你。
我嘗試了排序和切片方法,但它不起作用。
我是反應新手。
uj5u.com熱心網友回復:
您實際上是在獲取所有檔案并在客戶端過濾它們。如果用戶應該只讀取/寫入他們的檔案,那么這是不安全的,因為任何人都可以讀取所有用戶的檔案,而且效率低下,因為您每次都加載所有檔案只是為了顯示一個子集。相反,您應該使用查詢和安全規則,以便用戶只能讀取自己的資料。嘗試使用此查詢:
import { query, collection, getDocs, where } from "firebase/firestore"
const startOfToday = new Date();
startOfToday.setUTCHours(0,0,0,0);
// Documents created today (after 00:00 UTC)
const q = query(resultsCollectionRef, where("timestamp", ">", startOfToday));
const data = await getDocs(resultsCollectionRef);
const response = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
您不需要在客戶端進行任何過濾或排序,只需將資料映射到 UI。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/522780.html
