0

I'm trying to import JSON file that contains an array of blog-posts. All data contained in JSON file is imported successfully, except the Array of objects (edges)

This code is part of a unit test created with JestJS for a site build with Gatsby.

When I try to access edges array, I get "TypeError: Cannot read property 'edges' of undefined".

JS code:

import data from "./__mocks__/blog.json";

console.log(data);
data.allMarkdownRemark.edges.forEach((post) =>  {
  console.log(post);
})

Console.log(data):

{ data: { allMarkdownRemark: { edges: [Array] } }

My JSON file is formatted as a JSON object, so it is not necessary to use JSON.parse() JSON file:

{
  "data": {
    "allMarkdownRemark": {
      "edges": [
        {
          "node": {
            "id": "c60d0972-1f4a-55ae-b762-c24795fae501",
            "fields": {
              "slug": "/a-tu-cerebro-no-le-gusta-la-innovacion/"
            },
            "frontmatter": {
              "title": "A tu cerebro no le gusta la Innovación",
              "templateKey": "blog-post",
              "date": "September 16, 2017"
            }
          }
        },
        {
          "node": {
            "id": "1624f260-4c77-55d3-8297-4f0ad688f878",
            "fields": {
              "slug": "/la-mente-es-para-tener-ideas-no-para-almacenarlas/"
            },
            "frontmatter": {
              "title": "La mente es para tener Ideas™, no para almacenarlas",
              "templateKey": "blog-post",
              "date": "August 26, 2017"
            }
          }
        }
      ]
    }
  }
}

Do you know how to import correctly "edges" array of objects from JSON file?

2 Answers 2

2

The problem is your variable is called data and inside your json file you also defined data as a key. So you have to use data once as the variable and a second time as the key of the JSON file.

you have to access it like this:

data.data.allMarkdownRemark.edges.forEach((post) =>  {
  console.log(post);
})

Another solution would be to change the structure of your JSON file.

Sign up to request clarification or add additional context in comments.

Comments

0

You can:

import { data } from "./__mocks__/blog.json";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.