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");
}