skip to Main Content

I am rendering a product list from dummyjson
getting response from api

but showing products.map() is not a function

const fetchData = async () => {
    const response = await fetch("https://dummyjson.com/products");
    const data = await response.json();
    return setProducts(data);
  }

  useEffect(() => {
    fetchData();
  },[])

  console.log(products)

  return (
    <div>
    <ul>
    {products.map((product, index) => {
        return (
          <li key={index}>
            <h2>{product.title}</h2>
          </li>
        );
      })}
    </ul>
    </div>
  )

enter image description here

2

Answers


  1. Your data is an object. What you want to do is extract products from the JSON response, so in fetchData method you should call: setProducts(data.products).

    Login or Signup to reply.
  2. The api returns an object with a property products which contains the products array, so you need to do

    {products.products.map((product, index) => {
    

    Alternatively, you could store just the products array in state like so, and you can keep your existing map code.

    return setProducts(data.products);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search