Using JSON as a GraphQL data source in Gatsby

To get JSON data through Gatsby's GraphQL service, use the "gatsby-transformer-json" plugin.

Install by running "npm install gatsby-transformer-json --save" then adding the name of the plugin in the gatsby-config.js file:

plugins: [
    `gatsby-transformer-json`,
]

The plugin will find JSON files and add them as a GraphQL source derived from the name of the JSON file. (The file may need to be in a certain place - it's only working for me in the images directory.) Here's an example with a file test-data.json

[
    {"name" : "Larry"},
    {"name" : "Fred"},
    {"name" : "Joe"}
]

It will have two data sources: testDataJson and allTestDataJson. Here's a query with each and the result:

query MyQuery {
  testDataJson {
    name
  }
}

{
  "data": {
    "testDataJson": {
      "name": "Larry"
    }
  }
}



query MyQuery {
  allTestDataJson {
    edges {
      node {
        name
      }
    }
  }
}


{
  "data": {
    "allTestDataJson": {
      "edges": [
        {
          "node": {
            "name": "Larry"
          }
        },
        {
          "node": {
            "name": "Fred"
          }
        },
        {
          "node": {
            "name": "Joe"
          }
        }
      ]
    }
  }
}

Popular posts from this blog

Serve create-react-app from a subdirectory

Google sign-in with pwa_auth

Components in React: "class" and "functional"