Skip to content
This repository has been archived by the owner on Jul 16, 2020. It is now read-only.

Latest commit

 

History

History
89 lines (70 loc) · 3.2 KB

04-set-up-to-create-data-driven-pages-in-gatsby.md

File metadata and controls

89 lines (70 loc) · 3.2 KB

Set up to Create Data Driven Pages in Gatsby

📹 Video

Summary

In this lesson we learn how to load data from MDX (or any data source) and ensure the necessary folders exist.

⚡ Defining types

To satisfy the second condition in our list, we'll add an id which is of type ID!, and name and location, which are of type String!.

For the date, we going to use Gatsby's built in @dateformat directive.

We can do the same thing for the end date by copying the previous line and swapping out the names.

Lastly we want to get the URL which is a string.

gatsby-theme-events/gatsby-node.js

exports.sourceNodes = ({ actions }) => {
  actions.createTypes(`
    type Event implements Node @dontInfer {
      id: ID!
      name: String!
      location: String!
      startDate: Date! @dateformat @proxy(from: "start_date")
      endDate: Date! @dateformat @proxy(from: "end_date")
      url: String!
      slug: String!
    }
  `)
}

Note: for startDate and endDate, because the camel case does not line up with start_date and end_date, we include the following on the ends of each respectively:

@proxy(from: "start_date")
@proxy(from: "end_date")

We now need to define a custom resolver for our slug field, as we don't have a slug field in our events.

⚡ Setting up the slug

To gatsby-node.js, add the following:

gatsby-theme-events/gatsby-node.js

exports.createResolvers = ({ createResolvers }) => {
  const basePath = '/'

  const slugify = str => {
    const slug = str
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)+/g, '');
    return `/${basePath}/${slug}`.replace(/\/\/+/g, '/');
  }

  createResolvers({
    Event: {
      slug: {
        resolve: source => slugify(source.name)
      }
    }
  })
}

The resolver above returns the "slugified" version of the event name.

Documentation on Javascript Regular Expressions can be found in the resources. Otherwise, the instructor does a good job of explaining what the function does, so if you aren't familiar with Regular Expressions, just take the instructor's word for it.

⚡ Testing it all out

Running the following allows us to open our project in development mode:

yarn workspace gatsby-theme-events develop

Open up localhost:8000/___graphql to view our newly formatted event nodes

The event type Date allows us to view relative time or formatted time for our startDate and endDate.

Resources