Answered

How do I query Gatsby GraphQL for nested/linked content?

This is posted on behalf of a user:

How do I query GraphQL for nested content?

In my Global Header shared content item, I have a Content Item of Navbar Group which has a Content List of Navbar Items, some of which can have a Content List of Navbar Sub-Items.

I would like to retrieve that entire tree of header -> navbar group -> navbar items -> navbar sub-items but GraphQL only seems to contain the Reference Name of the Navbar Group. My current GraphQL query is the following:

query headerQuery {
     agilityGlobalHeader(properties: {referenceName: {eq: "globalheader"}}) {
        customFields {
           navbarGroup {
             referencename
           }  
        }
    }
}

2

Comments

2 comments
  • Official comment

    To query and resolve linked content in GraphQL for Gatsby, you'll need to add what's called a Resolver in your gatsby-node.js.

    This means you are telling GraphQL, when you query a specific property on node, it will actually run a function to go and get your linked content and return it.

    And example of this can be found here in our starter site:

    const agility = require('./src/agility/utils')

    //gatsy-node.js //CREATE RESOLVERS ******************************************************************************************* exports.createResolvers = (args) => { const { createResolvers, getNode, createNodeId, createNode, createContentDigest, configOptions } = args; const resolvers = { //on the 'agilityPost' node type... agilityPost: { //get the sitemap node that represents this item - useful for retrieving the URL for the item sitemapNode: agility.getDynamicPageItemSitemapNode(), //if we had a linked content field for 'author', this is how we'd get the author for this post in a single GraphQl query linkedContent_agilityAuthor: agility.getLinkedContentItem({ type: 'agilityAuthor', linkedContentFieldName: 'author' }) }, //if we had an 'Image Slider' module and it had a list of slides via a linked content field called 'slides', this is how we'd retrieve a list of those slides in a single GraphQL query agilityImageSlider: { linkedContent_agilitySlides: agility.getLinkedContentList({ type: 'agilitySlide', linkedContentFieldName: 'slides' }) } } createResolvers(resolvers) }
    Comment actions Permalink
  • Thanks! I was able to use this and reduce the number of GraphQL StaticQueries I had to run from four down to just one.

    0
    Comment actions Permalink

Please sign in to leave a comment.

Didn't find what you were looking for?

New post