Home > Enterprise >  Retrieve firebase collection based on uid in React.js
Retrieve firebase collection based on uid in React.js

Time:11-16

I must've read like 50-100 articles regarding this topic. Still I can't seem to solve it, nor understand it.

Within my Firestore database, I have a collection called "documents". Each document has their own "uid"-field. I am trying to retrieve the collection based on the uid of the user that's signed in.

I have come to the conclusion that my application isn't getting the user before the "unSubscribe" function runs. Probably since my user is null (which it initially is) when the useEffect first runs. But what should I do to make the function to wait for the user to become anything else than null? If that's the logic I should use.

PS. Also it seems like the where function isn't being used. How come?

import { useEffect, useState } from 'react'
import { onAuthStateChanged } from 'firebase/auth'
import { db, auth } from '../firebase/config'
import { collection, onSnapshot, query, where } from 'firebase/firestore'

import AddDocument from './AddDocument'
import Document from './Document'

const DocumentList = ({ title }) => {

    const [user, setUser] = useState()
    const [documents, setDocuments] = useState([])

    console.log(user)

    useEffect(() => {

      onAuthStateChanged(auth, currentUser => {
        setUser(currentUser)
      })

      const documentCollection = collection(db, 'documents').where('uid', '==', user.uid)

      const unSubscribe = onSnapshot(documentCollection, (snapshot) => {
        let results = []
        snapshot.docs.forEach(document => {
            results.push({...document.data(), id: document.id})
        })
        setDocuments(results)
      })

      return () => unSubscribe()

    }, [user])

    return (
        <div className="mt-16">
            <h5 className="text-gray-500">{title}</h5>
            <div className="grid grid-cols-8 mt-4">
                {documents && documents.map((props) => (
                    <Document key={props.id} {...props} />
                ))}
                <AddDocument />
            </div>
        </div>
    )
}

export default DocumentList

CodePudding user response:

The first step is that all code that needs the current user should be inside the onAuthStateChanged callback, as otherwise user won't have the correct value yet. So:

onAuthStateChanged(auth, currentUser => {
  setUser(currentUser)
  const documentCollection = collection(db, 'documents').where('uid', '==', currentUser.uid)
                                                                          //             
  • Related