user3225094
user3225094

Reputation: 81

Next.js JSON Nested

I'm trying to read the data of the JSON in Next.JS and can't get past the nested array. I can get the first .map logic to work. I want to print out the data in the below section of the JSON.

I can get Home, One and Two printed out. Just need to print Three and Four that is in the below array. I thought using "menuItem.below.map(childItem => (" would work.

TypeError: Cannot read properties of undefined (reading 'map')
{menuItem.below.map(childItem => (

Here is the Json.

[
{
"key": "standard.front_page",
"title": "Home",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "700d2d65-0307-471a-b843-c09ffcae0d9b",
"title": "One",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "51270262-f99d-4557-ad55-8bd8727ab15f",
"title": "Two",
"absolute": "http://localhost:8888/",
"relative": "/",
"below": [
{
"key": "f23a85d8-f430-47c8-87a1-c965d4078d0c",
"title": "Three",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "89b2d6b2-81d0-4d85-a0eb-8ce4e3dac80e",
"title": "Four",
"absolute": "http://localhost:8888/",
"relative": "/"
}
]
}
]
function MainMenu({ menuLists }) {
  return (
   <div>
      {menuLists.map(menuItem => (
        <div>
          <Link href={menuItem.absolute}><a>{menuItem.title}</a></Link>

          {menuItem.below.map(childItem => (
            <div>{childItem.title}</div>
          ))}
        </div>

      ))}
  </div>
  )
}

export async function getStaticProps() {

  const response = await fetch('http://localhost:8888/api/menu_items/main', config);
  const menuLists = await response.json();
  
  return {
    props: {
      menuLists: menuLists,
    },
  }
}

export default MainMenu

Upvotes: 1

Views: 1150

Answers (1)

Silvino Escalona
Silvino Escalona

Reputation: 321

The below property is not always present in the menuItems, so you must first make sure it exists:

{menuItem.below && menuItem.below.map(childItem => (
   <div>{childItem.title}</div>
))}

Upvotes: 1

Related Questions