Home > Back-end >  TypeError list.map is not a function
TypeError list.map is not a function

Time:01-21

Hi could someone tell me why I am getting the list.map is not a function error?

I don't know why the first 2 lan it is undefined

below is my code

singleProduct


import axiosLink from "../instance/axiosLink";

const SingleProduct = () => {
  const { id } = useParams();
  const [product, setProduct] = useState([]);
  useEffect(() => {
    axiosLink
      .get(`/api/products${id}`)
      .then(({ data }) => {
        setProduct(data);
      })
      .catch((error) => console.log(error));
  }, [id]);
  return (
    <div>
      <SingleProductComponent list={product} />
      {/* <RelatedProducts list={product} /> */}
      <Review />
    </div>
  );
};

export default SingleProduct;

SingleProductComponent

import React from "react";

const SingleProductComponent = ({ list }) => {
  return (
    <div>
      {list &&
        list.map((item, index) => {
          return (
            <div key={index}>
              <div className="SingleProduct">
               .........
                </div>
              </div>
            </div>
          );
        })}
    </div>
  );
};

export default SingleProductComponent;

axiosLink

import axios from "axios";

const axiosLink = axios.create({
  baseURL: "http://localhost:8000/",
  responseType: "json",
});

export default axiosLink;

Can you tell me the reason why? I get this error very often and I don't know the fix yet

this is my api structure

apiFormat

CodePudding user response:

you need to initialize your product state with an array like below

const [product, setProduct] = useState([])

CodePudding user response:

you can try

const SingleProduct = () => {
  const { _id } = useParams();
  const [product, setProduct] = useState();
  useEffect(() => {
    axiosLink
      .get(`/api/products${_id}`)
      .then(({ data }) => {
        setProduct(data);
      })
      .catch((error) => console.log(error));
  }, []);

CodePudding user response:

Check in network (inspect element -> network) if your data is correctly coming to you. Console log your data as well and check if its array. Practically this error says that your "list" is not an array, and it cannot map through it.

Also you should use useEffect(()=>{},[]) so it should fetch your api only once, and initialise your useState for product as empty array [].

  • Related