Home > Enterprise >  How to use data.map function in Reactjs
How to use data.map function in Reactjs

Time:01-29

I am working on Reactjs and using nextjs,Right now i am trying to fetch data using "map" function,How can i do this ? 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 (
   //want to use map function here
    );

}

CodePudding user response:

Well dummyjson will return you an object wich will contain { products, total, skip, limit } in your return you can write

{data.products.map((product) => <p key={product.id}>{product.title}</p>)}

paragraph in map can be your ArticleItem or everything you want.

CodePudding user response:

so you could do this, check if the state has any data in it then map through, if not show some other message. Not sure how your data state is structured, but this should help

return(
<div>
{
 data.length ? data.map(({id: number, title: string}) => <p key={id}>{title}</p>) : do something if data is empty
}
</div>)
  • Related