0

I have started working with gatsby and graphQL and am trying to fetch dat from rest API. I am able to loop through data and log it into console. However when using graphQL i am only getting one result. Please see my code below. I appreciate any help on what I am doing wrong.

exports.sourceNodes = async ({ boundActionCreators }) => {
 const { createNode } = boundActionCreators;
  console.log(createNode)
 const fetchData = () => axios.get(url)
 const res = await fetchData();
 console.log(res.data);

 res.data.blogArticle.forEach((article, index) => {

  return createNode({
   ...article,
   id: `£{index}`,
   children: [],
   parent: `__SOURCE__`,
   internal: {
    type: `BlogArticle`,
    content: JSON.stringify(article),
    contentDigest: crypto
     .createHash(`md5`)
     .update(JSON.stringify(article))
     .digest(`hex`)
   },
   heading: article.heading,
   subheading: article.subheading,
   content: {
    text: article.content.text,
    videoURL: article.content.videoURL,
    imageURL: article.content.imageURL
   }
  });
 });

 res.data.emptyLegs.forEach((leg, index) => {

  const emptyLegNode = {   

   from: leg.From,
   to: leg.To,
   aircraft: leg.Aircraft,
   seats: leg.Seats,
   date: leg.Date,
   price: leg.Price,

   id: `£{index}`,
   children: [],
   parent: `__SOURCE__`,
   internal: {
    type: `EmptyLegs`,
    contentDigest: crypto
     .createHash(`md5`)
     .update(JSON.stringify(res.data.emptyLegs))
     .digest(`hex`)
   },
  };

  createNode(emptyLegNode);
 });

 return;
};
AndrewB
  • 35
  • 2
  • 9
  • Can you give the code of your graphQL query ? As you named the `internal.type` **BlogArticle**, you should be able to query `allBlogArticle`... You can check the 2nd part of [this answer](https://stackoverflow.com/questions/49299309/gatsbyjs-getting-data-from-restful-api/49317803#49317803) – Nenu Apr 30 '18 at 11:20
  • thats what I am trying in graphiQl `query { allBlogArticle { edges { node { id heading content { text } } } } }` and I always get only one node back, however when I console articleNode it gives me all of them – AndrewB Apr 30 '18 at 11:23

1 Answers1

1

I think a simple typo is causing the problem.

Change:

return createNode({ id: `£{index}`, 

to:

return createNode({ id: `${index}`, 

and the same within the empty leg node id: ${index},

This should fix the error.

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
danielf
  • 11
  • 1