Cannot read property 'ref' of undefined

Fabrunet picture Fabrunet · Nov 12, 2017 · Viewed 10k times · Source

I'm building a simple web app with Vue + Firebase + Vuefire and I get "Uncaught TypeError: Cannot read property 'ref' of undefined" when I try to use my Firebase db variable inside a component.

In main.js

Vue.use(VueFire)

const firebaseApp = Firebase.initializeApp({ //setting })

// Export the database for components to use.
export const db = firebaseApp.database()

And in my component

// in Recipes.vue
import {db} from '../main.js'

export default {
  recipe: {
    source: db.ref('recipes')
    // Console says: "Uncaught TypeError: Cannot read property 'ref' of undefined"
  }
}

I followed the steps in this tutorial https://alligator.io/vuejs/vuefire-firebase/

This code db.ref('recipes') works if used inside main.js, but it never works once I import it inside my component.

Answer

Fabrunet picture Fabrunet · Nov 16, 2017

The problem was my Firebase code (including db variable) was inside main.js but it needed to be in it's own component. I created a firebase.js file :

import Firebase from 'firebase'

const firebaseApp = Firebase.initializeApp({
  # configuration
})

// Export the database for components to use.
export const db = firebaseApp.database()

Then in my component I simply imported my database variable :

import {db} from '../firebase'

Why didn't it work inside main.js? I'm not sure, maybe someone more knowledgeable can answer that.