Home > Software engineering >  How to fetch a single document from a firebase v9 in react app?
How to fetch a single document from a firebase v9 in react app?

Time:04-30

I have this useDocument Hook to fetch a single document from a Firebasev9 by passing id of the document. Can I get the document by passing a slug instead of id?

useDocument Hook

import { useEffect, useState } from "react"
// firebase import
import { doc, onSnapshot } from "firebase/firestore"

import { db } from "../firebase/config"

export const useDocument = (c, id) => {
  const [document, setDocument] = useState(null)
  const [error, setError] = useState(null)
  // realtime document data
  useEffect(() => {
    const ref = doc(db, c, id)

    const unsubscribe = onSnapshot(
      ref,
      (snapshot) => {
        // need to make sure the doc exists & has data
        if (snapshot.data()) {
          setDocument({ ...snapshot.data(), id: snapshot.id })
          setError(null)
        } else {
          setError("No such document exists")
        }
      },
      (err) => {
        console.log(err.message)
        setError("failed to get document")
      }
    )

    // unsubscribe on unmount
    return () => unsubscribe()
  }, [c, id])

  return { document, error }
}

CodePudding user response:

If you have the slug in document data then you can use a query to get that document as shown below:

const q = query(collection(db, c), where("slug", "==", SLUG))

onSnapshot(q, snap => {
  if (!snap.empty) {
    console.log(snap.docs[0].data())
  }
})

CodePudding user response:

you could do smth like

import { useEffect, useState } from "react"
// firebase import
import { doc, onSnapshot } from "firebase/firestore"

import { db } from "../firebase/config"

const useDocumentHook = (slug) => {
  const [doc, setDoc] = useState(null)
  useEffect(() => {
    const docRef = db.collection("posts").doc(slug)
    const unsubscribe = onSnapshot(docRef, (doc) => {
      setDoc(doc)
    })
    return () => unsubscribe()
  }, [slug])
  return doc
}
  • Related