Меню

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

I considered giving a comment under the answer by taggon to this very question, but well, i felt it owed more explanation for those interested in details.

Uncaught TypeError: Cannot read property ‘value’ of undefined is strictly a JavaScript error.

(Note that value can be anything, but for this question value is ‘map’)

It’s critical to understand that point, just so you avoid endless debugging cycles.
This error is common especially if just starting out in JavaScript (and it’s libraries/frameworks).
For React, this has a lot to do with understanding the component lifecycle methods.

// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children

import React, { useEffect } from 'react'

// Main component
const ShowList = () => {
  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {// dispatch call to fetch items, populate the redux-store})

  return <div><MyItems items={movies} /></div>
}

// other component
const MyItems = props =>
  <ul>
    {props.items.map((item, i) => <li key={i}>item</li>)}
  </ul>


/**
  The above code should work fine, except for one problem.
  When compiling <ShowList/>,
  React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
  And since `items={movies}`, 'props.items' is 'undefined' at that point.
  Thus the error message 'Cannot read property map of undefined'
 */

As a way to tackle this problem, @taggon gave a solution (see first anwser or link).

Solution: Set an initial/default value.
In our example, we can avoid items being ‘undefined’ by declaring a default value of an empty array.

Why? This allows React-DOM to render an empty list initially.
And when the useEffect or componentDid... method is executed, the component is re-rendered with a populated list of items.

// Let's update our 'other' component
// destructure the `items` and initialize it as an array

const MyItems = ({items = []}) =>
  <ul>
    {items.map((item, i) => <li key={i}>item</li>)}
  </ul>

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.

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

Master JavaScript


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.

Today We are Going To Solve × TypeError: Cannot read properties of undefined (reading ‘map’) in reactjs. Here we will Discuss All Possible Solutions and How this error Occurs So let’s get started with this Article.

Contents

  • 1 How to Fix × TypeError: Cannot read properties of undefined (reading ‘map’) Error?
    • 1.1 Solution 1 : Run this command
    • 1.2 Solution 2 : check your array
  • 2 Conclusion
    • 2.1 Also Read This Solutions
  1. How to Fix × TypeError: Cannot read properties of undefined (reading ‘map’) Error?

    To Fix × TypeError: Cannot read properties of undefined (reading ‘map’) Error just Run this command Just check your array exists or not. Learn this by given below example: <Filter> { product.color?.map((c) => ( <FilterColor color = {c} key = {c} /> ))}; </Filter>

  2. Fix × TypeError: Cannot read properties of undefined (reading ‘map’) Error?

    To Fix × TypeError: Cannot read properties of undefined (reading ‘map’) Error just check your array Just check your array exists or not. It will help you.

Solution 1 : Run this command

Just check your array exists or not. Learn this by given below example:

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

Solution 2 : check your array

Just check your array exists or not. It will help you.

Conclusion

So these were all possible solutions to this error. I hope your error has been solved by this article. In the comments, tell us which solution worked? If you liked our article, please share it on your social media and comment on your suggestions. Thank you.

Also Read This Solutions

  • Private: [Fixed] × TypeError: Cannot read properties of undefined (reading ‘map’)
  • [Fixed] Uncaught ReferenceError: process is not defined
  • [Fixed] Typescript Type ‘string’ is not assignable to type
  • [Fixed] UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte
  • [Fixed] UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xe9 in position 10: invalid continuation byte

Frankenstar

0 / 0 / 0

Регистрация: 16.09.2019

Сообщений: 38

1

16.09.2021, 00:00. Показов 11961. Ответов 5

Метки нет (Все метки)


Нужна ваша помощь. Пробую собирать данные API с помощью redux. Когда хочу отрисовывать данные то получаю эту ошибку:

Код

Cannot read properties of undefined (reading 'map')

Что я делаю не так? Спасибо большое вам. Вот мой код

Cartoons.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import {useDispatch, useSelector} from "react-redux";
import {cartoons_are_loaded} from "../redux/action_creators";
 
export let Cartoons = () => {
 
    let dispatch = useDispatch();
    let cartoons = useSelector(({cartoon_reducer: {cartoons}}) => cartoons);
 
    let fetchCartoons = async () => {
        try {
            let response = await fetch('https://api.sampleapis.com/cartoons/cartoons2D');
            let json = await response.json();
            console.log(json);
            dispatch(cartoons_are_loaded(json.data))
        } catch (e) {
            console.log(e)
        }
    }
 
    useEffect(() => {
       fetchCartoons();
    },[])
 
    return (<div>
        {cartoons.map(el => <div key={el.id}>{el.title}</div>)}
            </div>)
}

reducers.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import {CARTOONS_ARE_LOADED} from "./action_types";
 
let initialState = {
    cartoons: []
}
 
let cartoon_reducer = (state = initialState, action) => {
    switch (action.type) {
        case CARTOONS_ARE_LOADED: {
            return {
                ...state,
                cartoons: action.payload
            }
        }
 
        default:
            return state;
    }
}
 
export default cartoon_reducer;

action_types.js

Javascript
1
2
3
4
5
6
7
8
9
let CARTOONS_ARE_LOADED = 'CARTOONS_ARE_LOADED';
let ADD_FAVOURITE_CARTOON = 'ADD_FAVOURITE_MOVIE';
let DELETE_FAVOURITE_MOVIE = 'DELETE_FAVOURITE_MOVIE';
 
export {
    CARTOONS_ARE_LOADED,
    ADD_FAVOURITE_CARTOON,
    DELETE_FAVOURITE_MOVIE
}

action_creators.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
import {
    CARTOONS_ARE_LOADED,
    ADD_FAVOURITE_CARTOON,
    DELETE_FAVOURITE_MOVIE
} from "./action_types";
 
let cartoons_are_loaded = (payload) => ({type : CARTOONS_ARE_LOADED, payload});
 
export {
    cartoons_are_loaded
}

all_reducers.js

Javascript
1
2
3
4
5
6
import cartoon_reducer from "./reducers";
import {combineReducers} from "redux";
 
export let root_reducer = combineReducers({
    cartoon_reducer
})

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

16.09.2021, 00:00

5

129 / 67 / 31

Регистрация: 24.07.2018

Сообщений: 787

16.09.2021, 09:30

2

Frankenstar, скорее всего cartoons у тебя еще нет, а ты уже итерируешь его.
Я бы создал еще один компонет в таком случае, где будет подгружаться данные, ставить loading=true, после загрузки данных loading=false, и только потом отрисовывать компонент



0



0 / 0 / 0

Регистрация: 16.09.2019

Сообщений: 38

16.09.2021, 09:57

 [ТС]

3

MaksimkaI, Но в консоль я получаю данные, или я не правильно понимаю?



0



565 / 375 / 202

Регистрация: 30.04.2017

Сообщений: 704

16.09.2021, 15:10

4

что видно в консоли? json строка?

Цитата
Сообщение от Frankenstar
Посмотреть сообщение

dispatch(cartoons_are_loaded(json.data))

мб у json нет data параметра



1



0 / 0 / 0

Регистрация: 16.09.2019

Сообщений: 38

16.09.2021, 15:15

 [ТС]

5

Ovederax, Спасибо большое) У меня есть вопрос один. У меня еще есть таких 9 компонентов. Я пытаюсь отрисовывать 9-ю компоненту, ошибок у меня нет в консоль данные приходят, но они просто не видмальовуються. Вопрос, есть ли какое-то ограничение при выполнении запроса API? Спасибо)



0



565 / 375 / 202

Регистрация: 30.04.2017

Сообщений: 704

17.09.2021, 09:49

6

Цитата
Сообщение от Frankenstar
Посмотреть сообщение

Вопрос, есть ли какое-то ограничение при выполнении запроса API?

Цитата
Сообщение от Frankenstar
Посмотреть сообщение

в консоль данные приходят

можно держать много запросов к api
ошибка где-то в сохранении либо подписке на эти изменения



0



0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Cannot read properties of undefined reading length ошибка
  • Cannot read from port ошибка