skip to Main Content

I wanted to ask about gatsby and graphql as I’m having trouble retrieving the necessary data:

1- is it possible to insert getServerData inside a template in case of dynamically created pages? From Gatsby’s documentation I only find getServerData related documentation only within pages that stay at src/pages. I’m trying to pass a variable to getServerData via the createPages context in gatsby-node.

Alternatively:

2- Using the dynamic creation of pages via File System Routing, in this case […slug] I would like to pass the slug variable to a page query, in order to be able to filter a query of the type allCms.

query CollectionPageQuery($slug: String) {    
    allCmsPlp(
      filter: { parameters: { collection: { seo: { slug: { eq: $slug } } } } }
    ) {
      edges {
        node {
          parameters {
            collection {
              seo {
                slug
              }
              brandId
              categoryId
              generic
              clusterId
            }
          }
          sections {
            name
            data
          }
        }
      }
    }
  }

In the first case the getServerData does not work for me, in the second case I encountered build problems and it tells me that the slug variable does not exist and for this reason I assume it is not passed.

What do you recommend in the situation if I want to have:

  • pages created dynamically
  • page query that takes a variable
  • getServerData with SSR query

Thanks

2

Answers


    1. Yes, it possible to insert getServerData inside a template in case of dynamically created pages.

    2. Whatever you pass as a context in gatsby-node.js will appear as props.pageContext inside getServerData.

      export async function getServerData(props) { console.log(props.pageContext) }

    Login or Signup to reply.
  1. Create the pages dynamically in your gatsby-node file, e.g.: https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createPages

    When you create the pages, you pass a context. Put your variable (objectId, slug etc.) into this context.

    On the template side, that context will now be available in getServerData as { pageContext }.

    You can pull your variable from that context, use it to retrieve your page data, then return it from getServerData as "props".

    Your page data will then be available as {serverData} in your main page component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search