DEV Community

Discussion on: Using Vue Composition API with Firebase

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.