× TypeError: Cannot read properties of undefined (reading 'map')

Viewed 406233

When I try to run this code it gives me this error:

× TypeError: Cannot read properties of undefined (reading 'map')

Why does it happen? How can I make it work?

import React from 'react';
import Grid from '@material-ui/core/Grid';

import Product from './Product/Product';
import useStyles from './styles';

const products = [
  {id: 1, name: 'Shoes', description: 'Running Shoes.' },
  {id: 2, name: 'MacBook', description: 'Apple MacBook.' },
];

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

export default Products;
20 Answers

I had the same error and solved it by first asking if the array existed.

Example:

<Filter>
  { product.color?.map((c) => (
    <FilterColor color = {c} key = {c} />
  ))};
</Filter>

There is a property "products" in your component. That variable has higher priority than the map you have outside, and your .map is using it. I would recommend to rename one of them, to avoid variables with the same name.

Given the error, I would guess that that property wasn't passed to the component.

Also, the parameter of the map lambda is "products" too. Change it to "product", or it will fail.

The properties, products, that you're passing to your component (Products) are undefined. The Map method is taking in account the products that you have passed as properties is not the one that you have created outside the component itself.

If you want to map out the products array that you created outside of your components then just change its name as the array has the same name as the properties passed. If you want to use the products (from the property) then make sure that you're passing the properties in the component.

It's because you have taken the array "products" and the map item "products" by the same name. Change the map item to something else like "product":

const products = [
        {id: 1, name: 'Shoes', description: 'Running Shoes.' },
        {id: 2, name: 'MacBook', description: 'Apple MacBook.' },
    ];

const Products = ({ products }) => {
  const classes = useStyles();

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((product) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product/>
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

You are getting a blank array[]. For this, you are facing this error. You can solve this problem two ways:

{products && products.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product/>
    </Grid>
))};

Or

{products?.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product/>
    </Grid>
))};

Make sure to pass the products properties into the Product component. Change this:

{products.map((products) => (
              <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
                <Product/>

to this:

{products.map((products) => (
              <Grid item key={products.id} item xs={12} sm={6} md={4} lg={3}>
                <Product/>

Why? Because you're mapping an object (products) into a JSX element in your case which is the <Product/> component, so using { product.id } you're trying map an undefined object. Then make sure the products property you're trying to map out, is correctly passed into the parent component using the Products component.

        {products && products.map((product) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product />
          </Grid>
        ))};

At first, please check that products are exported. If yes, then change

{products.map((products) => (
  <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
  <Product/>

to

{products.map((products) => (
   <Grid item key={products.id} item xs={12} sm={6} md={4} lg={3}>
   <Product/>

Because here you map products as products, so you have to set the key like products.id.

You had named each iteration of the map method with products, but you are using product to catch each instance of the iteration.

Write it in this way and the issue would be resolved:

<Grid container justify="center" spacing={4}>
  {products ?.map((product) => (
    <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
      <Product/>
    </Grid>
  ))};
</Grid>

You can replace the map part like this:

{(products|| []).map(product) => ( // Your code ))}

Make sure properties is not undefined.

typeof products.map() !== undefined

Sometimes, it gives an error when you haven't used the variable of useState.

And I have made two other components. 1) Tour 2) Tours

 const [tours, setTours ] = useState([]);

Now, I have used this tours variable in App.js file using Tours components.

App.js

I have used tours in the App.js file.

App.js

Now, I'm taking the tours variable for using the .map() function in the Tours.js file.

const Tours = ({ tours }) => {
/...
{tours.map()
.../

Tours.js

You have to check that both files have the same spelling. Otherwise, it gives an error and also doesn’t work the UI of that particular file.

You should try this:

{products.map((product) => (
  <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
    <Product/>
  </Grid>
))};

Step 1: Add loading into user page - use useState

{const [loading, setLoading] = useState(true);}

Step 2: Set loading value to false at the end of async fetch function. If you’re using the try-catch method, put this code line inside the try method:

  {   setLoading(false)}

Step 3: Use a unary operation in the inside the render() part of the code

{ loading ? (
  <h2>loading</h2>
) :  {/* Enter code here */}}

You had this kind of error because you don't pass any information (props) inside the product component. So try this:

return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <Grid container justify="center" spacing={4}>
        {products.map((products) => (
          <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
            <Product product={product} />
          </Grid>
        ))};
      </Grid>
    </main>
  );
};

You should basically check the values received are undefined or not.

In Angular, you can use something like this: {{person?.name}}.

Use:

  <Grid container justify="center" spacing={4}>
    {products && products.map((products) => (
      <Grid item key={product.id} item xs={12} sm={6} md={4} lg={3}>
        <Product />
      </Grid>
    ))};
  </Grid>

Here changes in products && products.map() instead of products.map().

 { product.color?.map((c) => (
    <FilterColor color = {c} key = {c} />
  ))};

This would fix the issue but why does it appear well behind the scene react won't update the state immediately this concept is called scheduling that why when you products.map products are an empty array.

Check INITIAL_STATE in the reducer.

You must specify an array in the ID object you are calling in the reducer.

Example:

const INTIAL_STATE = {
    products: [],
    product: { name: "", brand_name: "", prices: "", color: "", images: []},
    error: "",
}

product.images.map(img => {
    return(
        <div key = {img.id} className = "img-itemm">
            <img src = {img.image} alt = {img.image} />
        </div>
    )
})
Related