The Log Blog

Using GraphQL in React/Gatsby

09 October, 2018

There are various data sources in Gatsby site like API, local files and CMSs.

Now take local file source as an example, install plugin by

  1. npm install --save gatsby-source-filesystem

  2. Add it into the gatsby-config.js.

plugins: [
    {
        resolve: `gatsbysource-filesystem`,
        options: {
            name: `src`,
            path: `${__dirname}/src/`,
        },
    },
]
  1. Restart the Gatsby dev server by pressing Ctrl+C and gatsby develop, and access GraphiQL.

    There will be 2 additional queries: file and allFile.

    Additional queries in GraphiQL

    Hint: Bring up autocomplete by Ctrl + Space.

    Here is a sample local file query:

{
    allFile {
        edges {
            node {
                id,
                nae,
                extension,
                relativePath,
                ctime
            }
        }
    }
}
  1. Press Ctrl + Enter to get the corresponding output.
{
  "data": {
    "allFile": {
      "edges": [
        ...
        {
          "node": {
            "id": "d05ca2cd-46fb-514c-813b-cdec1562e85d",
            "name": "gatsby-icon",
            "extension": "png",
            "relativePath": "images/gatsby-icon.png",
            "ctime": "2018-10-08T07:34:51.158Z"
          }
        },
        {
          "node": {
            "id": "fec6ae08-7bc8-5b26-81cb-e1bcefe24c6e",
            "name": "blog-post",
            "extension": "js",
            "relativePath": "templates/blog-post.js",
            "ctime": "2018-10-08T18:23:47.196Z"
          }
        },
        {
          "node": {
            "id": "390a3665-1a9d-5608-84b9-f513af8c93d7",
            "name": "index",
            "extension": "js",
            "relativePath": "pages/index.js",
            "ctime": "2018-10-08T18:24:20.443Z"
          }
        },
        ...
      ]
    }
  }
}

Hint: "node" in GraphQL refers to an object. So we now have an array of graphs, and each of them contains a node (object) with several fields.

Install transformer plugin to transform markdown files.

npm install --save gatsby-transformer-remark