How to add additional information to firebase.auth()

后端 未结 3 1985
梦毁少年i
梦毁少年i 2020-11-29 10:30

How can I add extra attributes phone number and address to this data set? It seems like Firebase documentation doesn\'t specify anything about that.

I have implemen

3条回答
  •  青春惊慌失措
    2020-11-29 10:57

    You could write some code that combines data from firebase auth and firestore document and expose that to the app as a single data entity. To take subscriptions and notify that changes to the whole app, you would be better served with event libraries like Rxjs. Bellow, I wrote the example below using a simple library that implements an event bus.

    // auth.js
    import { publish } from '@joaomelo/bus'
    import { fireauth, firestore } from './init-firebase.js'
    
    const authState = {
      userData: null
    };
    
    fireauth.onAuthStateChanged(user => {
      if (!user) {
        authState.userData = null;
        publish('AUTH_STATE_CHANGED', { ...authState });
        return;
      }
    
      // we must be carefull
      // maybe this doc does not exists yet
      const docRef = firestore
        .collection('profiles')
        .doc(user.uid);
    
      docRef
        // 'set' secures doc creation without 
        // affecting any preexisting data
        .set({}, { merge: true }) 
        .then(() => { 
          docRef.onSnapshot(doc => {
            // the first data load
            // and subsequent updates
            // will trigger this
            authState.userData = {
              id: user.uid, 
              email: user.email,
              ...doc.data()
            };
            publish('AUTH_STATE_CHANGED', { ...authState });
          });
        });  
    });
    
    // some-place-else.js
    import { subscribe } from '@joaomelo/bus'
    subscribe('AUTH_STATE_CHANGED', 
      authState => console.log(authState));
    

    You can expand on that in a post I wrote detailing this solution and also talking about how to update those properties. There is too a small library that encapsulates the answer with some other minor features with code you could check.

提交回复
热议问题