Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data map function is not working in Reactjs

I am working with Reactjs and using nextjs framework,Right now i am trying to fetch data (url is – https://dummyjson.com/products) using map function but i am getting following error

TypeError: Cannot read property 'length' of undefined

Here is my current code

import { useEffect, useState } from "react"
export default function Test() {
  const [data, setData] = useState<any>();
  useEffect(() => {
    const callData = async () => {
      const data = await fetch('https://dummyjson.com/products').then(data => data.json())
      console.log(data);
      setData(data)
    }
    callData()
  }, [])

  return(
    <div>
    {
     data.length ? data.map(({}) => <p key={data.id}>{data.title}</p>) : <h3>There are no records yet</h3>
    }
    </div>)

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • Initially data is undefined, so use optional chaining to check nested properties.
  • The returned data is an object; you want to access the products field.
  • Name the first parameter to the Array#map callback so you can actually access it.
{data?.products?.length ? data.products.map(product => <p key={product.id}>{product.title}</p>) 
       : <h3>There are no records yet</h3>}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading