Skip to content
Advertisement

Why It shows Undefined when I try Access object in array in Next js

I’m trying to display sub Products of the main product so what I have tried is to get the product code from the URL and try to fetch sub-products that match the main product code

 List of Products and Sub products
const data ={
 product:[
   {
   title:'Product1',
   slug:'001',
   category:'shirt',
   image:'./../../public/image1.jpg',
   },
   {
   title:'Product2',
   slug:'002',
   category:'shirt',
   image:'./../../public/image2.jpg',
   },
],
subProduct:[
   {
   title:'subProduct1',
   slug:'001',   
   image:'./../../public/image01.jpg',
   price:70
   },
   {
   title:'subProduct2',
   slug:'001',   
   image:'./../../public/image02.jpg',
   price:200
   },
   {
   title:'subProduct3',
   slug:'002',   
   image:'./../../public/image03.jpg',
   price:170
   },
   {
   title:'subProduct4',
   slug:'002',   
   image:'./../../public/image04.jpg',
   price:150
   },

],

}

  const  slug  = '001';  
  const product = data.product.find(x => x.slug === slug);
  const subProducts =  data.subProduct.filter(function(x) {
  return x.slug == slug;});
  
  
  console.log(subProducts.title)[enter image description here][1]

the issue is it shows Undefined when I try implement like {subProducts.title}

but when I console.log(subProducts) I get Array of subProducts that match with the slug of the Main Product

Advertisement

Answer

subProducts is an array of objects. You’re trying to get to title attribute of each item in that array but what you are actually doing with subProducts.title is that you’re trying to reference a title property on an array, which yields undefined, because the array has no such attribute. The array contains objects as individual items and those are the ones that have the title attribute.

So in react (which is part of next.js) when you need to render an array, try something like this:

const Component(props) => {
  const subproducts = [{title: 'Foo'}, {title: 'Baz'}]

  return (
    <div>
     {
      subproducts.map((subproduct) => (
        <div key={subproduct.title}>{subproduct.title}</div>
      ))
     }
    </div>
}

The key tag is required by react. More on this here

Advertisement