Search code examples
javascriptfirebasevue.jsfirebase-realtime-databasevuefire

Lifecycle hook for retrieving data from Firebase in a Vue component


I have a Vue 2 component, which uses Vuefire to bind declaratively with a Firebase realtime database:

import { db } from '../firebase/db'
export default {
    data: () => ({
        cats: []
    }),
    firebase: {
        cats: db.ref('cats')
    },
    mounted: function() {
        // loop over this.cats
    }
}

I want the component to loop over the cats property when it is mounted. The problem is that when it is mounted it has not yet retrieved the cats from the database. Is there a simple way to hook into this point? Or do I have to say goodbye to this neat way of fetching data and do it all in mounted?


Solution

  • As explained in the vuefire documentation for declarative binding:

    Any Database Reference provided in a firebase option will be bound at creation (after Vue's created hook) to the specified key on the component

    So you actually don't need to add anything in the mounted hook. If you want to trigger an action when the cats array is populated, you can use a standard Vue.js watch.


    If you don't want to subscribe to real time changes in the RTDB cats ref (i.e. do a binding in vuefire vocabulary) and only want to read once the cats node data when the component is mounted, you should use the standard Firebase JS SDK, as explained here in the vuefire doc.