Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

354
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!