Search code examples
reactjsjsonaxiosgatsby

How to get sub-node of JSON-File in gatsby/react


I want to create Azure Static Web App based on gatsby framework. I am quite new to gatsby/react/javascript development.

I created a GET-Request via axios in my gatsby-node.js file.

const getBlogs = endpoint => axios.get(`https://example.com/data-api/rest/blogs${endpoint}`);

 const getBlogsData = ids =>
  Promise.all(
    ids.map(async id => {
      const { data: blogs } = await getBlogs(`/glogs/${id}`);
      return { ...blogs };
    })
  );

 exports.createPages = async ({ actions: { createPage } }) => {
    const allBlogs = await getBlogsData(['1', '2', '3', '4']);

My reponse of allBlogs object looks like:

[
  { value: [ [Object] ] },
  { value: [ [Object] ] },
  { value: [ [Object] ] },
  { value: [ [Object] ] }
]

At the end I want to parse an array with the results/data to my gatsby-component My gatsby component looks like:

const ListBlogsComp = ({ pageContext: { allRezepte } }) => {
   return (
    <div style={{ width: 960, margin: '4rem auto' }}>
    <h1>ListBlogsComp</h1>
    {allBlogs.map(blog=> (
        <li key={blog.id}>
          <h2>{blog.id}</h2>
          <p>{glog.name}</p>
        </li>
      ))}
  </div>

  );
}

How can I access the data? How can I remove the "value" node to show the real data in my component/html-file?

I try to find a function like "value". Do I have to convert my variable into an other data type and then parse it?


Solution

  • you can remap the data structure and remove the extra "value" key, you can use the map function to transform the data in your gatsby-node.js file before passing it to your component.

    exports.createPages = async ({ actions: { createPage } }) => {
      const allBlogsData = await getBlogsData(['1', '2', '3', '4']);
    
      // Remap the data structure
      const allBlogs = allBlogsData.map(blog => blog.value[0]);//also i think i am seeing 2 array there so it might be blog.value[0][0]