Search code examples
firebasevue.jsnuxt.jsvuefirevuexfire

Nuxt this.$route is undefined


I have a dynamic route called products/_id which should load an product from Firestore. I am using VueFire to fetch the product from the Firebase database. Fetching the whole products collection works perfectly fine.

firestore: {
    product: firebase
      .firestore()
      .collection("products")
}

But getting the document with a certain id is where the trouble begins. Normally I would call

firestore: {
    product: firebase
      .firestore()
      .collection("products")
      .doc(this.$route.params.id),
  }

But now I get an error saying "TypeError: Cannot read property '$route' of undefined". Which is strange because if i log the route to the console I can actually see the id. Moreover, calling ".doc("DOCUMENT_ID") work perfectly fine.

Anyone knows how to fix this? I've tried a combination of methods and mounted hooks to retrieve the id but to no avail.

  mounted() {
    this.getProduct();
  },
  methods: {
    getProductId() {
      return this.$route.params.id;
    },
  },
  firestore: {
    products: firebase.firestore().collection("products").doc(this.getProductId),
  }

Brings up the same error...


Solution

  • firestore is specified as an object here, so it's evaluated immediately outside the context of the component, so this would not be the Vue component instance.

    To resolve this, specify firestore as a function that returns the intended object, as shown in the docs:

    export default {
      firestore() {
        // ✅ `this` is Vue component instance inside function
        return {
          products: firebase.firestore().collection("products").doc(this.getProductId),
        }
      }
    }