skip to Main Content

I’m trying to fetch data and then get my React App to map through the data to render each product on the page.

However it fails to find the data to perform the .map() and I assume that’s because the fetch hasn’t completed when it starts looking for the data.

How can I tell the map to occur after the data has been fetched? Here is an example of my code trying to get this working:

import React, { useState, useEffect } from 'react'


const App = () => {

  const [productData, getproductData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);
  
  const fetchData = async() => {
    fetch('https://dummyjson.com/products?limit=0')
      .then((res) =>
      res.json())
      .then((response) => {
      console.log(response);
      getproductData(response);
    })
  }
  
  return (
    <div className='products'>
      {productData.products.map(product => (
        <div className='product' key={product.id}>
          <div className='productInfo'>
            <div className='productTitle'>
              <div className='productBrand'>{product.brand}</div> 
              <div className='productName'>{product.title}            </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  )
}

export default App

3

Answers


  1. {productData.length > 0 && productData.products.map(...)}

    Login or Signup to reply.
  2. Before fetching data, productData.products is undefined.

    Replace productData.products.map to productData.products?.map will be helpful.

    And in this code snippet:

    `const fetchData = async() => {
        fetch('https://dummyjson.com/products?limit=0')
          .then((res) =>
          res.json())
          .then((response) => {
          console.log(response);
          getproductData(response);
        })
      }`
    

    I think getproductData(response.data) will be correct.
    Thanks.

    Login or Signup to reply.
  3. the issue arises because productData.products is undefined initially before the data is fetched. To handle this, you can add a check to ensure productData.products exists before map over it.

    {productData.products && productData.products.map(...)}
    or you can also use

    { productData?.products.map(...)}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search