DEV Community

Discussion on: Using Vue Composition API with Firebase

Collapse
 
razbakov profile image
Aleksey Razbakov

Hi! Thank you for article! It's a nice first step with vue-composition-api and firebase!
Even though there is a problem that useAuth is not reusable.

Let's say you want to have components like TheHeader, Account, UserAvatar where you would have setup function and there call useAuth. Every time you call useAuth you create a new listener onAuthStateChanged. It will work of course, but there is no single source of the truth anymore.

Here is how I did it, but I am still not sure if it is a right way to implement shared state. Probably we have to use inject and provide for this.

Collapse
 
aaronksaunders profile image
Aaron K Saunders

you really don't need to call onAuthStateChanged since firebase has the current user persisted. I was investigating using overmindjs or vuex to actually manage the state in combination with the composition api

Collapse
 
razbakov profile image
Aleksey Razbakov • Edited

I mean in your use/auth.js

export default function() {
  // our reactive properties...
  let state = reactive({
    user: null,
    loading: true,
    error: null
  });

  // make the firebase call to listen for change in auth state,
  // we have set initial loading status to true so nothing happens on UI 
  // side until loading is set to false
  firebase.auth().onAuthStateChanged(_user => {
    if (_user) {
      state.user = _user;
    } else {
      state.user = null;
    }
    state.loading = false;
  });

  // return all of the properties from the function
  return {
    ...toRefs(state)
  };
}

Every time you call const { user } = useAuth() in one of your components it will execute this part:
firebase.auth().onAuthStateChanged....

What if you need to access user in multiple components?

Btw, have you checked my implementation?

Thread Thread
 
paulvanbladel profile image
paul van bladel

completely valid point, the event registration should be executed only once in the app. also the state should be kept outside the hook function, in such a way it is shared over components initiating the hook.
The way how the state is exposed now makes the state mutable outside the hook function. If the state is exposed as a computed, it becomes unmutable, that's cleaner.