Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place to initialize Firebase in Nuxt.js app

I'm writing a web app with Nuxt.js and Firebase. In which file do I need to initialize the Firebase? In other words, where to put this code snippet?

var config = {
    apiKey: "xxxxxxxxxx",
    authDomain: "xxxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxxxx.firebaseio.com",
    projectId: "xxxxxxxxx",
    storageBucket: "xxxxxxxxxxx.appspot.com",
    messagingSenderId: "xxxxxxxxxx"
};
firebase.initializeApp(config);
like image 693
Yernar Avatar asked Apr 26 '18 16:04

Yernar


1 Answers

Create file firebase.js in folder plugins.

import firebase from 'firebase'
import 'firebase/firestore' //if use firestore

if (!firebase.apps.length) {
  firebase.initializeApp({
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx"
  })
}

firebase.firestore().settings({ timestampsInSnapshots: true })

const db = firebase.firestore()
const storage = firebase.storage() //if use storage

export { storage, db }

In component:

import { db } from '~/plugins/firebase.js'

data() {
  return {
    users: []
  }
},
mounted() {
  db.collection("users").get().then((querySnapshot) => {
    this.users = querySnapshot.docs.map(doc =>
      Object.assign({ id: doc.id }, doc.data())
    )
  })
}
like image 182
Adriano Resende Avatar answered Nov 18 '22 07:11

Adriano Resende