skip to Main Content

Working on app using reactJS, while using map function finding this error on console TypeError: data.map is not a function but the API data calling was successful found in console.log but to display data on window error is popping again here’s my code and also attaching console output image.

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom';

const Products = () => {
  const [data, setData] = useState([]);

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

  async function getProduct() {
    var res = await axios.get("http://localhost:9900/products");
    console.log(res.data);
    setData(res.data);
  }

  return (
    <>
      <div>
      {data.length > 0 && (
        data.map((product) => {
          return (
              <>
                  <div className="col-md-3 mb-4">
                      <div className="card h-100 text-center p-4 border-0 " key={product.productId} >
                          <NavLink to={`/products/${product.productId}`}><img src={product.productImage} className="card-img-top" alt={product.productTitle} height='250px' /></NavLink>
                          <div className="card-body">
                              <h5 className="card-title mb-0">{product.productTitle.substring(0, 12)}...</h5>
                              <h6 className="card-text text-center">Rating {product.productRating}</h6>
                              <p className="card-text lead fw-bold">${product.productPrice}</p>
                              <NavLink to={`/products/${product.productId}`} className="btn btn-outline-dark">Buy Now</NavLink>
                          </div>
                      </div>
                  </div>
              </>
          )
      })
      )}
    </div>
    </>
  )
}

export default Products

console image as output

3

Answers


  1. You’re receiving an Object from your API call, so use res.data.content.map() or only save the content key, which holds the array you’re looking for:

    async function getProduct() {
        var res = await axios.get("http://localhost:9900/products");
        if (res?.data?.content) {
            setData(res.data.content);
        }
    }
    
    Login or Signup to reply.
  2. As per your screenshot i can see your data has content element that has all your array data..so instead of data.map try data.content.map and see if it works for you..

    Login or Signup to reply.
  3. First of all your useState will be empty stryng = " ".
    You can try this code…

    useEffect(()=>{
          fetch("http://localhost:9900/products")
          .then(res=>res.json()
          .then(data=>setData(data)
      },[]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search