現在對于我的 web 應用程式,我正在嘗試使用 firebase 將資料從我的資料庫呈現到我的應用程式上。其中一個用戶(users 是資料庫中的一個集合)的 ID 為 QTKVV0WOBMhkq7Q6TPpDsGvprXf1。id 只是一個用戶 id(所以 currentUser.uid)。每個用戶都有一個習慣的集合。當我將 id QTKVV0WOBMhkq7Q6TPpDsGvprXf1 硬編碼到路徑中時,我能夠在本地主機的應用程式上顯示我的資料庫中的資料,但無論如何我都希望能夠顯示任何用戶的資料。
我已經嘗試了盡可能多的方法,但我似乎無法弄清楚。有什么建議?我試過創建一個包含 currentUser.uid 的變數,但這不起作用。我試過做其他事情,但都以錯誤告終......
所以理想情況下,我想換出 onSnapshot 路徑的中間,以便它只接受 current.uid
import React, { useEffect, useState } from "react";
import Habit from "./Habit";
import SearchBar from "./SearchBar";
import db, { useAuth } from "../firebase";
import { onSnapshot, collection } from "@firebase/firestore";
const HabitList = ({ mainSection, handleMainSection }) => {
// this initial state will be replaced with API request
const [habits, setHabits] = useState([
// { name: "Sample habit 1", id: 1 },
// { name: "Sample habit 2", id: 2 },
// { name: "Sample habit 3", id: 3 },
]);
const currentUser = useAuth();
var currentUserPath;
if(currentUser) {
console.log('uid: ', currentUser.uid)
currentUserPath=currentUser.uid;
console.log('currentUser: ', currentUser);
}
useEffect(
() =>
onSnapshot(collection(db, `users/QTKVV0WOBMhkq7Q6TPpDsGvprXf1/user_habits`), (snapshot) =>
setHabits(snapshot.docs.map((doc) => doc.data()))
//setHabits(snapshot.docs.map((doc) => doc.data())); // make sure that setHabits works and sets snapshot to habits
//console.log(habits); // habits should have the habits from firebase, not the initial habits we hardcoded
),
[]
);
return (
<div className="flex flex-col">
<SearchBar />
{habits.map(h => (
<Habit
habitName={h.name}
handleMainSection={handleMainSection}
key={h.id}
/>
))}
</div>
);
};
export default HabitList;
firebase.js (useAuth)
// Import the functions you need from the SDKs you need
import { useEffect, useState } from "react";
import { initializeApp } from "firebase/app";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { doc, setDoc } from "firebase/firestore";
import { v4 as uuidv4 } from "uuid";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyBN30k6RivLOuz7KToi_uD8V5s5cmyD9RM",
authDomain: "auth-development-62c42.firebaseapp.com",
projectId: "auth-development-62c42",
storageBucket: "auth-development-62c42.appspot.com",
messagingSenderId: "414005826367",
appId: "1:414005826367:web:7b987851735426ebedf98a"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();
export function signup(email, password) {
return createUserWithEmailAndPassword(auth, email, password);
}
export function login(email, password) {
return signInWithEmailAndPassword(auth, email, password);
}
// eventually write a logout function
export async function sendHabitToFirestore(uidPath, habitName) {
const db = getFirestore();
const habitId = uuidv4();
const pathDocRef = doc(db, "users", uidPath, "user_habits", habitId);
await setDoc(pathDocRef, {
name: habitName,
id: habitId
});
}
export function useAuth() {
const [currentUser, setCurrentUser ] = useState();
useEffect(() => {
const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
return unsub;
}, [])
return currentUser;
}
export default getFirestore();
錯誤:
Failed to compile
./src/components/HabitList.jsx
SyntaxError: C:\Users\jojoc\Desktop\local_dev\habitude\src\components\HabitList.jsx: Unexpected token (37:6)
35 | setHabits(newHabits); // consider using snapshot.docChanges() in later renders for efficiency
36 | console.log("New version of habits found!", newHabits); // note: habits isn't updated straight away, so we use the array passed to setHabits
> 37 | ),
| ^
38 | (error) => {
39 | // TODO: Handle errors!
40 | }
This error occurred during the build time and cannot be dismissed.
uj5u.com熱心網友回復:
根據您對 的實作useAuth,currentUser可能是簡短的null,這意味著在第一次渲染時,您useEffect附加到users/undefined/user_habits而不是您期望的用戶 ID。因為您的useEffect偵聽器不會偵聽 對 的更改currentUser,所以一旦會話得到驗證,它將永遠不會使用正確的用戶 ID 再次被呼叫。
useEffect(() => {
if (currentUser == null) { // signed out/not ready
// if habits is already empty, don't trigger a rerender
setHabits(habits.length === 0 ? habits : []);
return;
}
const userDocRef = collection(db, `users/${currentUser.uid}/user_habits`);
return onSnapshot(
userColRef,
(snapshot) => {
const newHabits = snapshot.docs.map((doc) => doc.data());
setHabits(newHabits); // consider using snapshot.docChanges() in later renders for efficiency
console.log("New version of habits found!", newHabits); // note: habits isn't updated straight away, so we use the array passed to setHabits
),
(error) => {
// TODO: Handle errors!
}
);
}, [currentUser]); // rerun if currentUser changes (e.g. validated, signed in/out)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368029.html
標籤:反应 火力基地 谷歌云firestore
上一篇:下拉欄位未顯示選定的保存值
