Home > Mobile >  Firestore uid not available after page reload
Firestore uid not available after page reload

Time:05-08

I am exporting a function returning firestore data useing the uid as identifier. The uid however is not available after reloading the page, causing af can't read null value error. I tried researching and happened upon the shown onAuthStateChanged, but this is causing the error: TypeError: Cannot read properties of undefined (reading 'indexOf'). Would appreciate the help.

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;
  };

CodePudding user response:

You should ideally run those queries only when the user state is loaded and initialize onAuthStateChanged() in useEffect(). Try refactoring the code as shown below:

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;
};
  • Related