Search code examples
javascriptfirebasevuejs2google-cloud-firestorevuefire

Set vuejs2 firebase config dynamically


Currently am setting firebase credentials in vuejs2 via

import Vue from 'vue';
import * as firebase from "firebase";
import VueFire from 'vuefire';

var config = {
   apiKey: "",
   authDomain: "",
   databaseURL: "",
   projectId: "",
   storageBucket: "",
    messagingSenderId: ""
};

Vue.use(VueFire);
firebase.initializeApp(config);

const firebasestore = firebase;
Vue.prototype.$firebase = firebasestore;

export { firebasestore }

What i want is to set the credentials dynamically example on created component not fixed values of apkey, authdomain, databaseUrl, projectid storage bucked

So something like. In my component i would like to set the credentials like

created(){
 this.$firebase.set ...// here set the config details
}

Can this be set this way rather than set the config on fixed values.


Solution

  • You could use a Vuex Store where you have a mutation that initializes Firebase.

    Then you can call an action to fetch Firestore.

    Here is an example (very unpolished POC...):

    Store

    import Vue from 'vue';
    import Vuex from 'vuex';
    import firebase from 'firebase/app';
    import 'firebase/firestore';
    
    Vue.use(Vuex);
    
    export const store = new Vuex.Store({
        state: {},
        actions: {
            fetchFirebase({ commit, state }) {
    
                firebase.firestore().collection("myCollection")
                    .doc("myDocument")
                    .get()
                    .then(doc => {
                        console.log(doc.data());
                    })
                    .catch(err => {
                        console.log(err);
                    });
    
            },
        },
        mutations: {
            initialiseFirebase(state, val) {
                firebase.initializeApp(val);
            },
        }
    });
    

    Component

    <template>
      <div>
        <button @click="initFirebase" class="button">Init Firebase</button>
        <button @click="fetchFirestore" class="button">Fetch Firestore</button>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {};
      },
    
      methods: {
        initFirebase() {
          const config = {
            apiKey: ".....",
            authDomain: ".....",
            databaseURL: ".....",
            projectId: "....."
          };
          this.$store.commit("initialiseFirebase", config);
        },
        fetchFirestore() {
          this.$store.dispatch("fetchFirebase");
        }
      }
    };
    </script>