Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

enter code here {
 "compdata": [
{
  "id": 1,
  "title": "FlexBox",
},
{
  "id": 2,
  "title": "Grid layout",
},

] }

enter code here **file in:-- src-data-data.json**
enter code here export const IndexQuery = graphql`
query IndexQuery {
dataJson {
compdata {
  id
  example
}

} } `

Blockquote giving me error Cannot read properties of undefined (reading 'compdata')

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
272 views
Welcome To Ask or Share your Answers For Others

1 Answer

You only need to follow the docs about Sourcing from JSON.

That said, you don't need to use GraphQL when sourcing from a JSON local file, you can just import the object such as:

import React from "react"
import JSONData from "../../content/My-JSON-Content.json"

const SomePage = () => (
  <div style={{ maxWidth: `960px`, margin: `1.45rem` }}>
    <ul>
      {JSONData.compdata.map((data, index) => {
        return <li key={`content_item_${index}`}>{data.title}</li>
      })}
    </ul>
  </div>
)
export default SomePage

In this case, you can import your JSON data as JSONData and loop it through the array of compdata.

However, if you still want to use GraphQL, you will need to use the gatsby-transformer-json plugin, what will create a queryable GraphQL node from your JSON source:

Install it by:

npm install gatsby-transformer-json

And use it your gatsby-config.js:

module.exports = {
  plugins: [
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/your/json/folder`,
      },
    },
  ],
}

The alias of the node will rely on your folder structure and your naming (which hasn't been provided), in the docs example, given a letters.json such as:

[{ "value": "a" }, { "value": "b" }, { "value": "c" }]

So in your GraphiQL playground (localhost:8000/___graphql) you will be able to query allLettersJson node:

 {
  allLettersJson {
    edges {
      node {
        value
      }
    }
  }
}

You can add a typeName option to fix your naming such as:

{
  resolve: `gatsby-transformer-json`,
  options: {
    typeName: `Json`,
  },
},

In that case, the created node will be allJson.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...