Alvin Crespo // Blog

TIL - Episode 5. Fetching local data with GatsbyJS.

December 29, 2019

Update: If you’re looking for code, checkout the testimonials history for my personal site here.

Today I was working on getting testimonials on my personal site, to do this I had to learn about “sourcing”, “transforming” and “querying” data in GatsbyJs. It took a couple of steps, but I was eventually able to get to a point where I could manage this data as a separate file.

The first step in this process was following along in the “Sourcing Data” guide.

The TL;DR here is that we use the sourceData Gatsby Node API to manually create some data that can be queried. We use this method along with createNode to add a node to the data.

Sample code:

// gatsby-node.js

exports.sourceNodes = ({ actions, createNodeId, createContentDigest }) => {
  const testimonials = [
    { cite: "Some Author", quote: "Some Quote" },
    { cite: "Some Author 2", quote: "Some Quote 2" },
  ]

  testimonials.forEach(testimonial => {
    const node = {
      cite: testimonial.cite,
      quote: testimonial.quote,
      id: createNodeId(`Testimonial-${testimonial.cite}`),
      internal: {
        type: "Testimonial",
        contentDigest: createContentDigest(testimonial),
      },
    }
    actions.createNode(node)
  })
}
// src/pages/testimonials.js

import React from "react"
import { graphql } from "gatsby"

const Testimonials = ({ data }) => {
  const {
    allTestimonial: { nodes: testimonials },
  } = data;

  return (
    {testimonials.map(t => (
        <blockquote
          cite={t.cite}
          dangerouslySetInnerHTML={{ __html: t.quote }}
        ></blockquote>
    ))}
  );
}

export const query = graphql`
  query {
    allTestimonial {
      nodes {
        id
        cite
        quote
      }
    }
  }
`

The second step in the process is moving this data outside to a file. To do that we need to source some files and then transform them.

A sourcing plugin “fetch[es] data from their source”.

A transformer plugin essentially “take[s] data fetched using source plugins, and process it into something more usable”.

For my purpose, I went with gatsby-source-filesystem and gatsby-transformer-json.

Sample code:

yarn add gatsby-transformer-json gatsby-source-filesystem
// gatsby-config.js

`gatsby-transformer-json`,
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `data`,
    path: `${__dirname}/src/data`,
    ignore: [`**/\.*`], // ignore files starting with a dot
  },
},
// src/pages/testimonials.js

export const query = graphql`
  query {
    allTestimonialsJson {
      edges {
        node {
          id
          cite
          quote
        }
      }
    }
  }

🎉🎉🎉 We have a nice GraphQL implementation of fetching testimonials!

Alright! Thank you for reading my learnings from today. Did you learn something new? Anything here that I got wrong or can improve on? Let me know at @alvincrespo.

Cheers!


Jump to top of page