Initialize Firebase references in two separate files in the new API

前端 未结 5 1673
粉色の甜心
粉色の甜心 2020-12-04 18:17

I have upgraded to the new API and don\'t know how to initialize Firebase references in two separate files:

    /* CASE 1 */
    // 1st file
    var config =         


        
5条回答
  •  情深已故
    2020-12-04 18:34

    I made the mistake by importing like this.

    import firebase from 'firebase'
    
    const firebaseConfig = {
      apiKey: 'key',
      authDomain: 'domain',
      databaseURL: 'url',
      storageBucket: ''
    };
    
    firebase.initializeApp(firebaseConfig);
    

    This worked fine for a few days but when I tried to sign in with custom tokens my auth object was not changed. I had to refresh the page for it to update so I could make certain calls to the database which were protected by my own auth credentials rules.

     ".read": "$uid === auth.uid || auth.isAdmin === true || auth.isTeacher === true",
    

    When I changed my imports to this it worked again.

    import firebase from 'firebase/app';
    import 'firebase/auth';
    import 'firebase/database';
    
    const firebaseConfig = {
      apiKey: 'key',
      authDomain: 'domain',
      databaseURL: 'url',
      storageBucket: ''
    };
    
    firebase.initializeApp(firebaseConfig);
    

    Then whenever I need to use Firebase in a certain module I import this(notice the import from firebase/app instead of firebase):

    import firebase from 'firebase/app';
    

    And talk to certain services like so:

    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        // Authenticated.
      } else {
        // Logged out.
      }
    });
    
    firebase.database().ref('myref').once('value').then((snapshot) => {
      // do stuff with the snapshot
    });
    

提交回复
热议问题