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

358
Visualizações
Firebase onSnapshot listener: How to handle if doc does not exist yet?

I am building an app where users can tag subjects they are interested in.

I am looking for best practices on how to handle the following issue:

I have a page that mounts an onSnapshot listener during page creation (example page path: site.com/tags/apple). This page allows the user to actually add the tag to their feed. First, I need to "watch" whether they add the tag to their feed or check to see if it already exists so that way I can toggle the state of a button icon to let them know that they already have added this tag to their feed.

I thought I'd use the onSnapshot listener to handle this logic like so (simplified for this question):

mounted() {

    loadwatchedTag() {
      const docRef = doc(db, `users/${this.userProfile.uid}/tags`, 'apple') //<-- example tag

      this.unsubscribe = onSnapshot(docRef, {
        next: (doc) => console.log('tag', doc.data()),
        error: (error) =>
          console.log('watchedTag listener error', error)
      })
    }

}

The problem is that on page load, I get the following error in console (because the tag does not yet exist):

tag, undefined

So, how to handle this issue on page load if the tag does not yet exist? Should I be doing something like this within the onSnapshot code?

if (docSnap.exists()) {
  console.log("tag exists!", docSnap.data());
} else {
  // doc.data() will be undefined in this case
  console.log("tag does not exist");
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Should I be doing something like this within the onSnapshot code?

if (docSnap.exists()) {
   console.log("tag exists!", docSnap.data());
} else {   
   // doc.data() will be undefined in this case  
   console.log("tag does not exist"); 
}

Yes this is exactly what you should do. And there is a "Note" dedicated to this case in the doc for the getDoc() method:

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

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