Struggling with the observer pattern using Firebase and Vue

Viewed 16

I am currently working on a personal project in which I use both Vue 3 (with the composition api) and Firebase. I have noticed that Firebase makes frequent use of the observer pattern, but this has caused some confusion for me.

For example, the suggested way of getting the current authenticated user is using the onAuthStateChanged observer. However, say I implement this observer in a component and I now have a child component that wants to take the current user object as a prop, I have written something like this:

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { ref } from "vue"

const curUser = ref()

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    curUser.value = user
  } else {
    curUser.value = null
  }
});

Now this works (somewhat) but I wonder if this is the wrong way to approach this. The issue is that the value curUser is undefined until onAuthStateChanged is called. This means that if curUser is passed as a prop to a child component the child has to be able to deal with it being undefined.

Is this approach correct or does this qualify as code horror? I have encountered this issue many times, another example where this exact same issue plays is with the onValue observer

0 Answers
Related