Search code examples
nuxt.jsapolloasyncdata

Apollo asyncData in Nuxt.js returns error


Nuxt.js full static (2.13) doesn't support apollo's smart queries, so I am going to use asyncData instead.

I have something like:

import homeQuery from '~/apollo/queries/home'

export default {
  asyncData(context) {
    let client = context.app.apolloProvider.defaultClient;
    client
      .query({
        query: homeQuery
      })
      .then(({ data }) => {
        return { data }
      })
  }
}

I expect to be able to use {{ data }} in my template. However, I get the following error:

ERROR [Vue warn]: Property or method "data" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

What is that I am doing wrong?


Solution

  • made it work changing it as:

    async asyncData({app}) {
      const homeresult = await app.apolloProvider.defaultClient.query({
        query: homeQuery
      })
      return { home: homeresult.data.home }
    },
    data () {
      return {
        home: {}
      }
    }
    

    however this doesn't seem to work on the default.vue layout when testing the static site with nuxt serve, but only on pages. I found it working on layout with fetch():

    async fetch() {
      const homeresult = await this.$apolloProvider.defaultClient.query({
        query: homeQuery
      })
      this.home = homeresult.data.home
    },
    data () {
      return {
        home: {}
      }
    }