简体   繁体   English

如何在 React 应用程序中从 firebase v9 获取单个文档?

[英]How to fetch a single document from a firebase v9 in react app?

I have this useDocument Hook to fetch a single document from a Firebasev9 by passing id of the document.我有这个 useDocument Hook 通过传递文档的 id 从 Firebasev9 获取单个文档。 Can I get the document by passing a slug instead of id?我可以通过传递 slug 而不是 id 来获取文档吗?

useDocument Hook使用Document 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 }
}

If you have the slug as a field in the document data then you can use a Query to get that document as shown below:如果您将 slug 作为文档数据中的一个字段,那么您可以使用 查询来获取该文档,如下所示:

// Query to fetch documents where slug field is equal to given SLUG 
const q = query(collection(db, c), where("slug", "==", SLUG))

onSnapshot(q, snap => {
  if (!snap.empty) {
    const data = snap.docs[0].data() 
    // snap.docs would be an array with 1 document
    // There could be multiple in case multiple posts have same slug by chance  
    console.log(data)
  } else {
    console.log("No documents found with given slug")
  }
})

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM