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 – 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('').then(data => data.json())
  }, [])

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


>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 ? => <p key={}>{product.title}</p>) 
       : <h3>There are no records yet</h3>}

Leave a Reply