Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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. 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 }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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:

// 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")
  }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda