I've been encountering some challenges with Apollo, GraphQL, and Nuxt. I'm not sure if it's specifically related to Nuxt or Vue.
I'm attempting to utilize WordPress as a headless CMS via the WP-GraphQL plugin. Here is my query:
Essentially, I created a graphql folder with a posts.js file inside that contains my query:
import gql from 'graphql-tag'
export const myQuery = gql`
query myQuery {
posts {
nodes {
id
title
date
slug
author {
node {
name
}
}
featuredImage {
node {
uri
sourceUrl
srcSet
}
}
}
}
}
`
Then, all I need to do is print my data in the template. First, here's the script part:
<script>
import { myQuery } from '~/graphql/posts'
export default {
data() {
return {
posts: [],
}
},
apollo: {
posts: {
prefetch: true,
query: myQuery,
},
},
watch: {
async $route() {
await this.$nuxt.refresh()
window.scrollTo(0, 0)
},
},
transition: 'home',
async mounted() {
this.posts = await this.$apollo.query({ query: myQuery })
this.posts = this.posts.data.posts.nodes
this.loading = false
}
</script>
Next is the template:
<template>
<section class="featured-projects">
<div class="featured-projects__wrapper">
<article v-for="post in posts" :key="post.id">
<p>{{ post.id }}</p>
<h2>{{ post.title }}</h2>
<span>{{ post.date }}</span>
</article>
</div>
</section>
</section>
</template>
Everything is functioning smoothly!
Now, I want to display the post author's name as well. When I tried this:
<span>{{ post.author }}</span>
It actually printed this:
{
"node": {
"name": "max max",
"__typename": "User"
},
"__typename": "NodeWithAuthorToUserConnectionEdge"
}
It makes sense, as the author is an object with nested items. So, based on what I receive and following the GraphQL API structure, to display the post author's name, I think I should do something like this instead:
<span>{{ post.author.node.name }}</span>
However, when I try this, I encounter the error "Cannot read property 'node' of undefined." Unfortunately, I'm unsure how to access what I want.