alexa
Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

Rendering json data in react getting error: TypeError: Cannot read properties of undefined (reading 'item')' json data

Rendering json data in react getting  error: TypeError: Cannot read properties of undefined (reading 'item')' json data

If backEndData is the object you're showing, it's obvious it does not have a items property. So backEndData.items is undefined. You can't access any property on undefined (you'll just get the error you're getting).

You probably mean

  <div className='main'>
    {backEndData.item.map(product => (<p>{product.name}</p>))}
  </div> 

For the sake of good naming conventions, I think the best thing to do is rename item in your json to items, while changing the above to

  <div className='main'>
    {backEndData.items.map(product => (<p>{product.name}</p>))}
  </div> 

, accordingly.

Another note: if backEndData is fetched from the server and it's not available initially, you either condition the component rendering based on its value, in parent component (e.g:

 <div>
  {data && (<Main backEndData="data" />)}
</div> 

) or, alternatively, you can use optional chaining (?.) inside <Main>:

 <div className='main'>
  {backEndData.items?.map(product => (<p>{product.name}</p>))}
</div>

70 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online