Search code examples
gatsby

GraphQL gets context data and query results from dynamic pages


I have dynamically created pages that include data in a context with the createPage functions:

groups.forEach(async node => {
    const id = node.name
   
    actions.createPage({
      path: 'group/'+id,
      component: require.resolve(`./src/pages/groups/index.js`),
      context: { id: id },
    })
  })
....

Then I have the resulting page with a graphql query:

import * as React from "react"
import { graphql } from 'gatsby'

const GroupPage = ({data}) => {
 
        return (
            <main >               
                <ul>
                    {
                        data.allAgents.edges.map(node => (
                        <li key={node.node.name}></li>
                        ))
                    }
                </ul>
          
            </main>
        )     
}


export const query = graphql`
query($id: String!)  {
    allAgents (filter: { group: {eq: $id } } ) {
        edges {
          node {
            id
            name
            group
          }
        }
      }
}
`

export default GroupPage

export const Head = () => <title>Group</title>

How can I access the context's page values ?

Thanks


Solution

  • You have exposed a prop named pageContext what contains the context object passed in the gatsby-node.js as you can see in the docs:

    On your pages and templates, you can access your context via the prop pageContext like this:

    import React from "react"
    
    const Page = ({ pageContext }) => {
      return <div>{pageContext.house}</div>
    }
    
    export default Page
    

    In your case:

    const GroupPage = ({data, pageContext}) => {
     
           console.log("the context is:", pageContext)
    
            return (
                <main >               
                    <ul>
                        {
                            data.allAgents.edges.map(node => (
                            <li key={node.node.name}></li>
                            ))
                        }
                    </ul>
              
                </main>
            )     
    }
    

    Note: if you want to use the pageContext to query or to filter your GraphQL query (in your case by id), you can get rid of pageContext since the value it's automatically lifted to the GraphQL query, hence the $id: String! will be automatically used. pageContext is useful if you want to display different data.

    Note 2: the loop you're using to create pages should be synchronous: groups.forEach(node => {...})