Home > other >  Uncaught TypeError: products.map is not a function ; ReactJS
Uncaught TypeError: products.map is not a function ; ReactJS

Time:05-06

I am working on the MERN stack project. Here I need to display fetched data from backend in the Home screen. But the data from backend is not shown in the home screen.

Here is my code;

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


function HomeScreen() {
  const [products, setProducts] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get('/api/products');
      setProducts(result.data);
    };
    fetchData();
  }, []);
  return (
    <div>
      <h1>Featured Products</h1>
      <div className="products">
        {products.map((product) => (
          <div className="product" key={product.slug}>
            <Link to={`/product/${product.slug}`}>
              <img src={product.image} alt={product.name} />
            </Link>
            <div className="product-info">
              <Link to={`/product/${product.slug}`}>
                <p>{product.name}</p>
              </Link>
              <p>
                <strong>${product.price}</strong>
              </p>
              <button>Add to cart</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default HomeScreen;

Uncaught TypeError: products.map is not a function. This is the error I have got.

CodePudding user response:

The .map function is only available on array.

It looks like data isn't in the format you are expecting it to be (it is {} but you are expecting []).

Check what type "result.data" is being set to, and make sure that it is an array.

CodePudding user response:

Try to put a condition if the products exist or not :

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


function HomeScreen() {
    const [products, setProducts] = useState([]);
    useEffect(() => {
        const fetchData = async () => {
            const result = await axios.get('/api/products');
            setProducts(result.data);
        };
        fetchData();
    }, []);
    return (
        <div>
            <h1>Featured Products</h1>
            <div className="products">
                {products && products.map((product) => ( // add this "products &&" before products.map
                    <div className="product" key={product.slug}>
                        <Link to={`/product/${product.slug}`}>
                            <img src={product.image} alt={product.name} />
                        </Link>
                        <div className="product-info">
                            <Link to={`/product/${product.slug}`}>
                                <p>{product.name}</p>
                            </Link>
                            <p>
                                <strong>${product.price}</strong>
                            </p>
                            <button>Add to cart</button>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}

export default HomeScreen;
  • Related