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>)
}
CodePudding user response:
- Initially
data
isundefined
, 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>}
CodePudding user response:
Try to initialize data
state with an empty array:
const [data, setData] = useState<any>([]);
You should also change
data.map(({}) => <p key={data.id}>{data.title}</p>)
to
data?.map(({id,title}) => <p key={id}>{title}</p>)
CodePudding user response:
//Follow this code. your data in the products array so if you want to map then you have to pass array.
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?.products)
}
callData()
}, [])
return(
<div>
{
data.length ? data.map((product) => <p key={product.id}>{product.title}</p>) : <h3>There are no records yet</h3>
}
</div>)
}
CodePudding user response:
The problem with your code is that you are missing the destructuring of elements in the map function. The correct way would be
{
data.length ? data.map(({title, id}) => <p key={id}>{title}</p>) :
<h3>There are no records yet</h3>
}