Cannot read properties of undefined reading map ошибка

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;

Peter Mortensen's user avatar

asked Sep 6, 2021 at 21:56

udenyi's user avatar

4

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>

answered Nov 17, 2021 at 17:47

jake's user avatar

jakejake

1,2611 gold badge8 silver badges2 bronze badges

3

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.

Peter Mortensen's user avatar

answered Sep 6, 2021 at 22:01

Iván's user avatar

IvánIván

9556 silver badges20 bronze badges

1

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>
))};

Peter Mortensen's user avatar

answered Jun 25, 2022 at 5:12

Md. Shafiqul Islam's user avatar

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.

Peter Mortensen's user avatar

answered Sep 6, 2021 at 22:50

Abdullah Ch's user avatar

Abdullah ChAbdullah Ch

1,5971 gold badge11 silver badges27 bronze badges

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>
  );
};

Peter Mortensen's user avatar

answered Oct 13, 2021 at 9:45

Dawood Ahmad's user avatar

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>

Peter Mortensen's user avatar

answered May 25, 2022 at 6:29

Bhupendra Singh's user avatar

Use:

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

  return (
    <main className={classes.content}>
      <div className={classes.toolbar} />
      <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>
    </main>
  );
};

Just add «products &&«. This will check if the map is defined or not.

Peter Mortensen's user avatar

answered Nov 19, 2022 at 7:56

vishal 's user avatar

vishal vishal

411 bronze badge

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 */}}

Peter Mortensen's user avatar

answered Mar 20, 2022 at 16:30

sai nath's user avatar

Use:

 { 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, and that is why when you access products.map, products are an empty array.

Peter Mortensen's user avatar

answered Sep 19, 2022 at 10:32

Bilal Mohmand's user avatar

1

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.

Peter Mortensen's user avatar

answered Oct 13, 2021 at 9:36

Primrose's user avatar

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.

Peter Mortensen's user avatar

answered Nov 19, 2021 at 4:15

Faizan  Arif's user avatar

1

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

Peter Mortensen's user avatar

answered Dec 11, 2021 at 10:13

Mushahid's user avatar

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

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

Peter Mortensen's user avatar

answered May 5, 2022 at 11:22

Sagar M's user avatar

Sagar MSagar M

1,15813 silver badges10 bronze badges

You can replace the map part like this:

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

Peter Mortensen's user avatar

answered Jun 5, 2022 at 14:50

Mohit Singh's user avatar

2

Make sure properties is not undefined.

typeof products.map() !== undefined

answered Aug 26, 2022 at 9:57

JUGG's user avatar

JUGGJUGG

413 bronze badges

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

answered Oct 28, 2021 at 15:44

Ahmed eltarouty's user avatar

2

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.

Peter Mortensen's user avatar

answered Dec 18, 2021 at 15:02

Avi's user avatar

You should try this:

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

Peter Mortensen's user avatar

answered Jan 11, 2022 at 12:35

Morteza Mazrae's user avatar

1

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>
  );
};

Peter Mortensen's user avatar

answered Apr 12, 2022 at 7:53

Borhen Kalboussi's user avatar

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().

Peter Mortensen's user avatar

answered Jun 28, 2022 at 7:20

riddhi dobariya's user avatar

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

// add "products &&" before the map method

answered Oct 30, 2022 at 23:39

Programmer Injamam's user avatar

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>
  );
};

answered Dec 11, 2022 at 21:05

achraf lafkiri's user avatar

0

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>
    )
})

Peter Mortensen's user avatar

answered Oct 1, 2021 at 8:39

Baxisli Imran's user avatar

The «Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)» error occurs in JavaScript, whenever you try to use the array map method on a variable that is undefined. This can usually happen in React, whenever you need to loop through an array of elements and display them.

{posts.map(post => <Card details={post} />)}

Copied to clipboard!

However, the array on which you are executing the map is undefined. This means that JavaScript sees the following code, and throws the above error:

// Trying to run map on undefined
{undefined.map(post => <Card details={post} />)}

// Or simply try to run in your console
undefined.map()

Copied to clipboard!

Try to run the above code in your console, and you will end up with the very same error. This is a common pitfall that can be easily avoided using the following solution.

Get your weekly dose of webtips

Get access to 300+ webtips 💌

Level up your skills and master the art of frontend development with bite-sized tutorials.

We don’t spam. Unsubscribe anytime.

Looking to improve your skills? Check out our interactive course to master React from start to finish.

Master React


How to Fix the Error?

In order to fix the error, you need to make sure that the array is not undefined. In order to do this, the simplest way is to use optional chaining.

{posts?.map(post => <Card details={post} />)}

Copied to clipboard!

You can use optional chaining by introducing a question mark after the variable. You can also use a logical AND, or use an if check prior to rendering to prevent running into issues.

// Using logical AND
{posts && posts.map(post => <Card details={post} />)}

// Using an if check
if (!posts) {
    return null
}

// Here post will not be undefined anymore
return (
    <React.Fragment>
        {posts.map(post => <Card details={post} />)}
    </React.Fragment>
)

Copied to clipboard!

Problem:

Recently, we start developing a new web application project by React JS. But when we try to show the products list, we got this error. We will try to describe why this error occurs and how to fix it. The code is given below,

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>
  );
};

The code has thrown an error saying,

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

Solution:

The problem arises because we’re attempting to map an undefined object (products) into a JSX element. In our case which is the <Product />  component, so using { product.id } we’re trying map an undefined object. Then make sure the products property we’re trying to map out, is correctly passed into the parent component using the Products component. 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/>

Thank you for reading the article. If you have any query please comment below.

Хочу данные в MyPost закинуть вверх в index.js но как видно из вопроса выходит ошибка которую я не могу понять как решить или хотя бы разобраться в чем дело
My post:

import React from "react";
import s from './MyPost.module.css';
import Post from './Post/Post';
import DialogsItems from "../../Dialogs/DialogsItems/DialogsItems";
import Message from "../../Dialogs/Message/Message";

const MyPost = (props) => {
    let newPosts = props.posts.map(m => <Post message={m.message} /> );

    return (
        <div className={s.postBlock}>
            <h3>My posts</h3>
        <div>
            <textarea className={s.postSub}>Hello</textarea>
            <br/>
            <button>Add post</button>
        </div>
            <div className={s.posts}>
                {newPosts}

            </div>
        </div>

    );
}
export default MyPost;

Profile:

import React from "react";
import s from './Profile.module.css';
import MyPost from './MyPosts/MyPost'
import ProfileInfo from "./ProfileInfo";
import Post from "./MyPosts/Post/Post";

const Profile = (props) => {

    return (
        <div className={s.content}>
            <ProfileInfo />
            <MyPost posts={props.Posts}/>

        </div>
    );
}
export default Profile;

App.js:

import React from 'react';
import './App.css';
import { BrowserRouter, Routes, Route} from "react-router-dom";
import Nav from './components/Nav/Nav';
import Profile from './components/Profile/Profile';
import s from './components/Header/Header.module.css';
import Dialogs from './components/Dialogs/Dialogs';




function App(props) {

  return (

      <BrowserRouter>
          <div className="App-wrapper">

              <header className={s.Header}>
                  <img className={s.logo} src='https://avatars.mds.yandex.net/i?id=88b5d56ab1e2969c8c7ada7728e6ce5b-5880151-images-thumbs&n=13' alt='Это ссылка'/>
              </header>
              <Nav />
              <div className='app-wrapper-content'>
                  <Routes>
                      <Route path='/' element={<Profile />}/>
                      <Route path='/Dialogs/*' element={<Dialogs dialog={props.dialog} messages={props.messages} />} />
                      <Route path='/Profile' element={<Profile posts={props.Posts}/>}/>
                  </Routes>
              </div>
          </div>
      </BrowserRouter>
  );
}

export default App;

index:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import state from "./Redux/state";
let Posts = [
    {message:'Hello, my name Angela'},
    {message:'Join my team, we will win this game'},
];


ReactDOM.render(
  <React.StrictMode>
    <App Posts={Posts}  />
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

when I use the map method inside the showData function it works, but when I use it while rendering, it shows an error.

export class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      word: "",
      data: [],
    };
  }

  handelWordChange = (e) => {
    this.setState({ word: e.target.value });
  };

  showData = async () => {
    
    let url = `https://api.urbandictionary.com/v0/define?term=${this.state.word}`;
    let rawData = await fetch(url);
    let parsedData = await rawData.json();
    this.setState({ data: parsedData });

    this.state.data.list.map((e) => {
      console.log(e.definition);
    });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handelWordChange}
        />
        <button onClick={this.showData}>Show</button>

        {this.state.data.list.map((e) => {
          return <h1>{e.definition}</h1>;
        })}
      </div>
    );
  }
}
 

I am learning to react and I came through this error can anyone please help me out.

asked Sep 27, 2021 at 11:36

Karan Sharma's user avatar

This Error is appearing because when your component load on the first render then your data variable value is an empty array, Add the conditional check before applying the map on the array.

{this.state.data && this.state.data.list && this.state.data.list.map((e) => {
      return <h1>{e.definition}</h1>;
})}

answered Sep 27, 2021 at 11:46

Mohsin Baig's user avatar

1

This error is when you are accessing properties/indices from something undefined.

Use optional chaining to make sure you are only accessing properties of objects which themselves are defined.

{this.state.data.list?.map((e) => {
          return <h1>{e.definition}</h1>;
        })}

answered Sep 27, 2021 at 11:39

Tushar Shahi's user avatar

Tushar ShahiTushar Shahi

15.8k1 gold badge14 silver badges37 bronze badges

2

Понравилась статья? Поделить с друзьями:
  • Cannot read properties of null reading classlist ошибка
  • Cannot load serious sam 3 ошибка
  • Cannot import paramcount ошибка
  • Cannot find efi directory grub install ошибка
  • Cannot find appropriate setup exe file matlab ошибка