How to get fields from linked document inside a slice

Say I have a type homepage that allows a slice where one of the repeatable fields is a relationship field to another type called book.

This book type has a title and an author field.

How can I get my homepage data together with the title and author of the field?

I would prefer the non-graphql way. I tried the graphql way, got that working, but for some reason my data stopped getting fetched and was always outdated compared to the data I saved in prismic..

Hi Jasper,

Welcome to the community!

If you don't want to do this with GraphQL and want to use the REST API, then you have 2 options (Though we should explore why you weren't getting up to date data in GraphQL):

Fetchlinks:

GraphQuery (Not GraphQL):

These are both query options to get linked data.

Let me know if you need anymore help.

Thanks.

Hi Phil,

Thanks for the quick response.

I've already consulted the posted links, but they don't exactly point me in the right direction. They don't have examples for when you want to grab fields from documents that are linked within a slice.

I really tried my best combining the existing information, but alas I didn't find any success.

The reason why I ditched the GraphQL route was twofold:

  • For some reason, my cache was always showing old data, and I always had to restart my server for it to show new content. Stack is NextJs by the way. I'm also not too familiar with GraphQL yet, so that may be a reason as well.
  • When I added a new slice to my type and added data to it, it refused to return me the correct data, It seemed to be related to Apollo / graphQL WARNING: heuristic fragment matching going on!. The strange thing is that the query in GraphQL playground was giving me the expected result, but copying it to my code, it returned no data at all..

Your GraphQuery would be used to query EVERYTHING on the main document, including specifying the linked field. Like in the example below:

const mySuperGraphQuery = `{
  homepage {
    field1
    field2
    body {
      ...on link_slice {
        non-repeat {
          book_link {
            title
            author
          }
        }
      }
      ...on image_gallery {
        repeat {
          image
        }
      }
    }
  }
}`

api.getByUID('homepage', 'example-uid',
  { 'graphQuery': mySuperGraphQuery }
).then(function (document) {
  // document contains the document content
});

As for the issue with GraphQL, it sounds like maybe you might be creating a statically generated site with Next.js and not clearing the cache each time.

I got it to work with your suggestions, thanks.

About the GraphQL error, I was suddenly getting

Missing field type in {
  "__typename": "HomepageBodyHero"
}
Missing field fields in {
  "__typename": "HomepageBodyHero"
}

This was after adding a new slice type in my homepage type. Is this something that is going wrong on your end?

@Phil I tried my hand at my GraphQL implementation again, and after removing the "faulty" slice, it suddenly started working again.

Re-adding even a simpler version of the slice, gives me errors again.

How can I provide you with the necessary information to check what's going wrong?

EDIT: This missing field error is also the reason I'm currently getting data: null

When you add this Slice are you publishing a document that is using it? or are you simply specifying it without using it? because if no documents have it published, then it won't be available through the API and will cause errors.

While I'm not entirely sure what the reasoning is behind it causing errors if it's just not used, I can confirm that it is currently being used.

The thing is that the query fails, even without requesting the fields. I have no mention of my newly added slice in my GraphQL query.

So even with a filled in field and the slice not being requested, I am getting an error and thus as a result null.

For reference, this is the query I'm currently executing. Do note that this query works perfectly in the GraphQL sandbox you guys provide, but it does not in my Next.js project.

      {
        homepage(uid: "homepage", lang: "en-us") {
          body {
            ... on HomepageBodyGuides_preview {
              type
              fields {
                guide {
                  ... on Polar_guide {
                    name
                    intro_text
                    image
                  }
                }
                testje
              }
            }
          }
        }
      }

When running the query locally, I get these errors

WARNING: heuristic fragment matching going on!
Missing field type in {
  "__typename": "HomepageBodyHero"
}
Missing field fields in {
  "__typename": "HomepageBodyHero"
}

And this is the result of my query

{ data: null, loading: false, networkStatus: 7, stale: true }

When I remove the slice from the instance of my Homepage (so not from the content type, but the actual content itself), the query works again.

{
  data: { homepage: { body: [Array], __typename: 'Homepage' } },
  loading: false,
  networkStatus: 7,
  stale: false
}

Am I doing something wrong?

@Phil Any update about the above?

Hey Jasper,

OK, so it's a Next.js query specific issue. I'm not exactly sure what the issue could be, I'm reaching out to my team mates to get some help on this.

Are you using the Apollo plugin? Can you send me the full code for the page where you are doing the query?

Hi Phil,

This is the component's data side

Home.getInitialProps = async ({ req }) => {
  const doc = await client.query({
    query: gql`
      {
        homepage(uid: "homepage", lang: "en-us") {
          body {
            ... on HomepageBodyGuides_preview {
              type
              fields {
                guide {
                  ... on Polar_guide {
                    name
                    intro_text
                    image
                  }
                }
                testje
              }
            }
            ... on HomepageBodyHero {
              type
              fields {
                test
              }
            }
          }
        }
      }
    `,
  });
  return {
    doc: doc,
  };
};

export default Home;

Where the client is this

import { PrismicLink } from "apollo-link-prismic";
import { InMemoryCache } from "apollo-cache-inmemory";
import ApolloClient from "apollo-client";
import gql from "graphql-tag";
import possibleTypes from "./prismicIntrospectionResults";

export const client = new ApolloClient({
  link: PrismicLink({
    uri: "https://XXX.prismic.io/graphql",
    accessToken: "XXX",
  }),
  cache: new InMemoryCache({
    possibleTypes,
  }),
});

Hey Jasper,

So I believe this has to do with Introspection fragment matching, can you check this document out?

Hi Phil,

That seems to have solved the problem.

2 questions however:

  • Are my queries so intricately different from a standard user's queries? If not, how come this small piece of code is not built-in to the libraries provided by you, or just even in the Getting started sections?
  • How will this work once my code is in production? Will my server need to restart, rebuild the fragmentTypes for every save that is done? That can not be intended, right?

Honestly I'm not sure, I'm going to need help from the @Team-Education on that one?

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

@Phil @jasper1 This can be added to to our feature request tracker as something to improve. And yes, I believe you'll need to rebuild your fragmentTypes if anything changes. We'll look into it and see if there is something that can be done to improve this in the future, but for now you'll at least have this as a workaround.