Vue-apollo: Nuxt and apollo, undefined data

Created on 27 Mar 2019  路  1Comment  路  Source: vuejs/vue-apollo

Hello,

What i have

I'm using apollo inside nuxt application. I get my datas from a headless CMS.
I have a
/blog/_slug.vue

<!-- display title -->
<template>
  <h1>{{post.title}}</h1>
</template>

<script>
import gql from 'graphql-tag'

// get datas from a graphqlApi, depending on the route
export default {
    apollo: {
        post: {
          prefetch({route}){
              return{
                  slug: this.$route.params.slug
              }
          },
          variables(){
              return{
                  slug: this.$route.params.slug
              }
          },
          query: gql `query BlogPost($slug: String!) {
              post: blogpost(filter: {slug: {eq: $slug}}) {
                  title
                  body
              }
          }
          `
        }
    }
}
</script>

What is going wrong

When I go to http://localhost:3000/blog/mypost by url, everything's fine.
But when I get there from a link in another page, I get an error :
'Cannot read property title of undefined'.

What is working fine

And if I hit reload, everything is fine again...

Furthermore, if I only display my {{post}} variable instead of {{post.title}}, I don't get any error, and my datas are displayed as expected !

My Apollo config :

import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import schema from '~/plugins/apollo/schema.json' 
const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData: schema
})

export default function(context){
    return {
        httpEndpoint: 'https://graphql.datocms.com/',
        getAuth:() => 'Bearer faketoken540324069840', 
        cache: new InMemoryCache({ fragmentMatcher })
    }
}

Any clue on this will be appreciated, thanks for your help !

Most helpful comment

Solved ...

I just had to add "post" as an empty object in my component data ...

export default {
  data (){
    return {
      post: {}
    }
  },
  ...

>All comments

Solved ...

I just had to add "post" as an empty object in my component data ...

export default {
  data (){
    return {
      post: {}
    }
  },
  ...
Was this page helpful?
0 / 5 - 0 ratings