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 avoiditemsbeing ‘undefined’ by declaring adefaultvalue of an empty array.Why? This allows React-DOM to render an empty list initially.
And when theuseEffectorcomponentDid...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.

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
- 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> - 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
reducers.js
action_types.js
action_creators.js
all_reducers.js
__________________
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 у тебя еще нет, а ты уже итерируешь его.
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 строка?
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 |
|
Вопрос, есть ли какое-то ограничение при выполнении запроса API?
в консоль данные приходят можно держать много запросов к api
0 |
