Traverse through nested nodes using GraphQL in Nuxt

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:

WP-GraphQL interface

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.

Answer №1

The issue you're facing stems from trying to access data before it has finished loading.

Depending on your JavaScript settings, you can try one of the following solutions:

<span>{{ post?.author.node.name }}</span>

or

<span>{{ post ? post.author.node.name : '' }}</span>


Referencing the Vue Apollo documentation, it might also be related to query duplication.

<script>
import { myQuery } from '~/graphql/posts'

export default {
  data() {
    return {
      posts: [], // initialized
    }
  },

  apollo: {
    posts: {
      prefetch: false, // avoid SSR
      query: myQuery,
      update: data => {
        console.log('Replacing old posts with new data', data.posts)
        return data.posts
      }
    },
  }
}
</script>

Additionally, in scenarios where there are multiple authors for a post (such as co-authors), consider updating the author rendering logic like this:

<template>
    <section class="featured-projects">
      <div class="featured-projects__wrapper">
        <article v-for="post in posts" :key="post.id">
          <p>{{ post.id }}</p>
          <div v-if="Array.isArray(post.author)">
            First author: {{ post.author[0].node.name }}
          </div>
          <div v-else-if="post.author">
            Author: {{ post.author.node.name }}
          </div>
          <div v-else="post.author">
            No author specified
          </div>
        </article>
      </div>
    </section>
  </section>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to efficiently calculate totals in an HTML table using JavaScript/jQuery

I have a gridview that displays product details and includes a quantity textbox that is not linked to any database. For each row, I want it to show the cost (price * quantity) and the total cost for all rows in a label below. However, I am encountering a f ...

Finding Your Way with a Quick Navigation Bar

I am facing a simple issue, but due to my lack of experience in design, I find it challenging. Currently, I am working on a basic PHP website project. I have a navigation bar and want the content of a specific panel to change when a navigation button is c ...

Error: Mongoose Schema Undefined when Route is Added in Separate File

For the sake of organizing my code, I made the decision to separate all of my schemas and routes into different files within my directory, and then required them in my app.js. Each schema corresponds with each route. This method has worked for all but one ...

Troubleshooting: Why is the Vue search feature in v-data-table not functioning properly

My issue involves using computed values to populate my v-data-table, and I am struggling to resolve the search functionality. Additionally, I would like to re-enable column sorting if possible. Below is the code for my v-Data-Table: <v-data-table ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

Transferring a Sharepoint 2010 List Item between folders

Currently, I am facing an issue while attempting to transfer a list item from one folder to another. Despite utilizing a code that I discovered (the link to the source of the code can be found below), I keep encountering an error message stating "Value doe ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

obtain the equivalent offsetX value for touch events as for mouse events

Greetings! I am currently attempting to retrieve the offsetX and Y values of a touch event, which ideally should match the offsetX value of a mouse event. In order to achieve this, I have implemented the following code: ev.offsetX = ev.targetTouches[0].p ...

Tips on eliminating the 'first', 'previous', 'next', and 'last' buttons in the twbs pagination plugin

I am searching for a straightforward pagination solution that only displays page numbers without control buttons like "first," "previous," "next," and "last." I have looked through the options available in twbs-pagination's github documentation and on ...

Tips for dealing with event bubbling in React

Looking for a way to add an onBlur event to the left panel so that it closes when the user clicks on the right panel. I attempted using onMouseLeave but the closing animation isn't as smooth as desired. Additionally, I'd like for users to close t ...

What is the best way to structure a JSON data string for transmission from a WebView to JavaScript?

Seeking a solution for passing multiple values from an Android WebView to JavaScript. The challenge is that the string received in JS appears completely raw with control characters. The specific issue arises when sending the following string from Java: f ...

Update the text on Bootstrap Tooltip when it is clicked

I am looking to update the content of my tooltip when it is clicked. Below is the current code snippet I am using: function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); ...

ReactJS experiencing issue with the functionality of the all-the-cities library

Encountering an issue where importing the library all-the-cities causes reactjs to malfunction and display the following error: TypeError: fs.readFileSync is not a function (anonymous function) C:myproject/node_modules/all-the-cities/index.js:6 3 | cons ...

Creating a Cloudinary Angular URL: A Step-by-Step Guide

Currently, I am utilizing Cloudinart on Angular and my goal is to create a Cloudinary URL. <cl-image public-id="public_id"> <cl-transformation height="270" width="480" crop="fill"/> & ...

Challenges with setting up a bunyan child logger

This app consists of two files, foo.js and bar.js, both importing Logger.js to generate a child logger using bunyan. Issue: While foo.js is functioning properly, bar.js is encountering difficulty locating MyService.log defined in Logger.js. This problem s ...

Guide on how to retrieve a single document (mongoose/mongoDB)

Storing data in a database is crucial for many applications. { "_id": "62fa5aa25778ec97bc6ee231", "user": "62f0eb5ebebd0f236abcaf9d", "name": "Marketing Plan", "columns": [ { ...

Using jQuery to input a value that returns the [object Object]

While working with jQuery in asp.net, I encountered an issue where the value assigned to a hidden field (hfstockcode) is returning [object Object]. The console output shows v.fn.v.init[1]. How can I retrieve the correct value for the hidden field? $(docum ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

Managing multiple POST requests in Node.js - a comprehensive guide

When I use the request library to communicate with other servers via API, sending multiple POST requests simultaneously presents a challenge. My typical syntax involves setting up options for each request and handling them individually. However, when faced ...