Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to initialize firebase in Vue js app?

  // Initialize Firebase
  var config = {
    apiKey: "...",
    authDomain: "my-project.firebaseapp.com",
    databaseURL: "https://my-project.firebaseio.com",
    projectId: "my-project",
    storageBucket: "my-project.appspot.com",
    messagingSenderId: "..."
  };
  firebase.initializeApp(config);

When I initialize Firebase in index.html or main.js, in both cases i have an error

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

I have to initialize it in my component (Dashboard). Is it proper way to initialize firebase in one of my components? Why i can do this in e.g. main.js ?

like image 610
luk Avatar asked Nov 07 '22 00:11

luk


1 Answers

One way is to have a firebaseConfig.js file like the following

import firebase from 'firebase/app';
import 'firebase/firestore';

var config = {
    apiKey: "....",
    authDomain: ".....",
    databaseURL: ".....",
    ......
};
firebase.initializeApp(config);

const db = firebase.firestore();

// date issue fix according to firebase
const settings = {
    timestampsInSnapshots: true
};
db.settings(settings);

export {
    db
};

and import and use it in each of your Components (where you need Firebase) as follows:

<template>
    ......
</template>
<script>
const firebase = require('../firebaseConfig.js');
export default {
  name: 'xxxxx',
  data() {
    return {
      ....
    };
  },
  methods: {
    fetchData() {
      firebase.db
        .collection('xxxxx')
        .get()
        ..... //Example of a call to the Firestore database
    }
  }
  .... 
};
</script>
like image 185
Renaud Tarnec Avatar answered Nov 10 '22 00:11

Renaud Tarnec