How can i use a prop as part of the firebase path using VueFire?

412 Views Asked by At

I have an list of objects in firebase called meals. In this component I want to show information on only one meal so I pass an id field as a prop and I want to get only that meal from firebase.

This is what I tried. It didn't work because this.id was undefined:

import db from '@/firebase'

export default {
    name: 'meal',
    props: {
        id: {
            type: String,
            required: true
        }
    },
    firebase: {
        meals: db.ref('meals').child(this.id)
    }
}

Did I do something wrong or does the firebase call happens before the props are initialized?


EDIT:

I managed to do it using the created hook but it looks pretty bad. Is there any other way?

created() {
        this.$bindAsObject('meal', db.ref('meals').child(this.id))
    }
2

There are 2 best solutions below

0
On

According to the official doc of VueFire, your way to use the creation hook is exactly correct. Firebase basically works in a different lifecycle with Vue.js, so you need to use that doller syntax provided VueFire.

0
On

This one burned me pretty hard. You have to use the firebase function AND create a reference to your variable like this:

import db from '@/firebase'

export default {
    name: 'meal',
    props: {
        id: {
            type: String,
            required: true
        }
    },
    firebase() {
        const id = this.$props.id // Pass the reference instead of the prop directly
        return {
          meals: db.ref('meals').child(id)
        }
    }
}