页面重新加载后 Firestore uid 不可用

Firestore uid not available after page reload

我正在导出一个使用 uid 作为标识符返回 firestore 数据的函数。然而,重新加载页面后uid 不可用,导致af can't read null value 错误。我尝试研究并偶然发现了显示的 onAuthStateChanged,但这导致了错误:类型错误:无法读取未定义的属性(读取 'indexOf')。非常感谢您的帮助。

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import {
   getAuth, 
   onAuthStateChanged } from "firebase/auth";
import { useState, useEffect} from "react";
import { 
   getFirestore, 
   collection, 
   getDocs, 
   addDoc, 
   setDoc, 
   doc } from 'firebase/firestore';

const firebaseConfig = {
 apiKey: "AIzaSyCJtckBTE3-ub4JP6NcEJX_PKao7r0YJRw",
 authDomain: "dtustudenthub.firebaseapp.com",
 projectId: "dtustudenthub",
 storageBucket: "dtustudenthub.appspot.com",
 messagingSenderId: "400034264848",
 appId: "1:400034264848:web:f065a4bb76463063dd5795",
 measurementId: "G-M5K2EJKLEL"
 };

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

export const auth = getAuth(app);

const db = getFirestore();


export const GetAppointmentsFromFirebase = () => {
   const [user, setUser] = useState({});
   onAuthStateChanged(auth, (currentUser) => {
       setUser(currentUser);
     });
   const appointmentColRef = collection(db, 'users', user?.uid, 'appointments');
   let [schedulerData, setSchedulerData] = useState([])
   useEffect(() => {
   getDocs(appointmentColRef)
      .then((snapshot) => {
          let appointmentData = []
          snapshot.docs.forEach((doc) => {
              appointmentData.push({ ...doc.data() })
              })
           setSchedulerData(appointmentData);
           console.log(appointmentData)
          })
          .catch(err => {
              console.log(err.message)
          })
      }, []); 
   return schedulerData;
  };

理想情况下,您应该 运行 只有在加载用户状态并在 useEffect() 中初始化 onAuthStateChanged() 时才进行这些查询。尝试重构代码,如下所示:

export const GetAppointmentsFromFirebase = () => {
  const [user, setUser] = useState({});
  let [schedulerData, setSchedulerData] = useState([])

  useEffect(() => {
    onAuthStateChanged(auth, async (currentUser) => {
      // Check if currentUser is null
      if (currentUser) {
        setUser(currentUser);

        // Read user ID directly from user object
        const appointmentColRef = collection(db, 'users', currentUser.uid, 'appointments');
        const snapshot = await getDocs(appointmentColRef)

        const data = snapshot.docs.map((d) => ({
          id: d.id,
          ...d.data()
        }))

        setSchedulerData(data);
        console.log(data);
      } else {
        console.log("No user logged in")
      }
    });
  }, []);
  return schedulerData;
};