最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to solve Uncaught TypeError: data.map is not a function - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jun 14, 2023 at 11:42 M. Deinum 126k22 gold badges233 silver badges249 bronze badges asked Jun 14, 2023 at 11:00 Deepak PariharDeepak Parihar 271 gold badge1 silver badge3 bronze badges 3
  • Did you mean to setData(res.data.content)? res.data appears to be an object. – DBS Commented Jun 14, 2023 at 11:07
  • Add TypeScript (via) to catch such errors already in the IDE. You'd have to generate TypeScript definitions for your back-end models. New contenders are TypeSpec from Microsoft and Taxi from Orbital. – cachius Commented Jun 14, 2023 at 13:00
  • I would check the data type of res.data when it is returned. It's possible you need to unwrap or deconstruct the response. Saying it won't map is a clear indicator that your data state is changing from an array object. – boredProjects Commented Jun 14, 2023 at 13:11
Add a ment  | 

2 Answers 2

Reset to default 2

In the screenshot I can see that the axios.get() response object res.data contains the array in the content property. So either replace

  • data.map by data.content.map in the JSX or
  • setData(res.data) by setData(res.data.content) in getProduct()

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);
    }
}
发布评论

评论列表(0)

  1. 暂无评论