Home > Back-end >  How to get documents from collection with userid as collection name in react
How to get documents from collection with userid as collection name in react

Time:07-14

Currently I want to get all the documents from a collection with the userid of the current user as the name of that collection in react from firestore.

The current problem I face is that react throws an error because it tries to fetch the collection before the userid is fetched so it is searching in an empty path for the collection.

This is the code I currently use for getting the documents in the collection:

import { useAuth, db } from '../Firebase'

...
    
const currentUser = useAuth();

useEffect(
   () =>
   onSnapshot(collection(db, 'Patienten/'   currentUser.uid   '/Patienten'), (snapshot) =>
     setPatienten(
       snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })),
     ),
   ),
 [],
)

Relevant code in Firebase.js:

export function useAuth() {
  const [currentUser, setCurrentUser] = useState()

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user))
    return unsub
  }, [])

  return currentUser
}

So what this code does is return the documents in the collection 'Patienten//Patienten' which does not exist and throws an error. Is there a solution to this problem?

CodePudding user response:

It sounds like you'll your database effect depends on that UID, which means you should add that state variable as a dependency to useEffect:

useEffect(() => {
  if (currentUser) {
    onSnapshot(collection(db, 'Patienten/'   currentUser.uid   '/Patienten'), (snapshot) => {
      setPatienten(snapshot.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id
      })), )
    })
  }
}, [currentUser]);

Your useAuth/user effect should no longer return the current user, and instead only set it in the currentUser state variable (which then triggers the re-evaluation of your database effect).

  • Related