Skip to content

Instantly share code, notes, and snippets.

@michaelrambeau
Last active December 9, 2017 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelrambeau/14eac1b0437e522175e81ab073701d42 to your computer and use it in GitHub Desktop.
Save michaelrambeau/14eac1b0437e522175e81ab073701d42 to your computer and use it in GitHub Desktop.
Add data to Gatsby pages using GraphQL

Steps to add data to a Gatsby project, using GrahQL to query an external API at build time:

  • add sourceNode to gatsby-node.js
  • Check the data from the Graphiql UI: http://localhost:8000/___graphql
  • Inject data to components or template by exporting a query property, in addtion of the default export.
import React from 'react'
import SalariesBlock from '../blocks/SalariesBlock'
import ExperienceBlock from '../blocks/ExperienceBlock'
import Meta from '../elements/Meta'
const DevelopersTemplate = props => (
<div className="template">
<Meta section={props.section} subSection="developers" />
<SalariesBlock {...props} />
<ExperienceBlock {...props} />
</div>
)
export default DevelopersTemplate
export const query = graphql`
query projects {
github {
count
childrenProject {
name
stars
homepage
description
slug
}
}
}
`
exports.sourceNodes = async ({ boundActionCreators }) => {
const { createNode } = boundActionCreators
// Create nodes here, generally by downloading data
// from a remote API.
console.log('>>> Fetching...')
const url = 'https://bestofjs-api-dev.firebaseapp.com/stateofjs2017.json'
const response = await axios.get(url)
const projects = response.data.projects.slice(0, 5)
console.log('>>> Done!', projects.length)
projects.forEach(project =>
createNode({
id: project.slug,
name: project.name,
slug: project.slug,
description: project.description,
homepage: project.homepage,
stars: project.stars,
parent: 'github',
children: [],
internal: { contentDigest: 'yyy', type: 'project' }
})
)
createNode({
id: 'github',
count: projects.length,
children: projects.map(project => project.slug),
parent: null,
internal: { contentDigest: 'xxx', type: 'github' }
})
// We're done, return.
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment