I get the following error in my ReactJS code:
TypeError: Cannot read property ‘map’ of undefined
This is based on the following code:
JavaScript
x
50
50
1
import React, { Component } from "react";
2
import { connect } from "react-redux";
3
import { ListGroup, ListGroupItem } from "reactstrap";
4
import { bindActionCreators } from "redux";
5
import * as categoryActions from "../../redux/actions/categoryActions";
6
7
class CategoryList extends Component {
8
componentDidMount() {
9
this.props.actions.getCategories();
10
}
11
render() {
12
return (
13
<div>
14
<h3>Categories</h3>
15
<ListGroup>
16
{this.props.categories.map(category => (
17
<ListGroupItem key={category.id}>
18
{category.categoryName}
19
</ListGroupItem>
20
))}
21
</ListGroup>
22
<h5>The Category: {this.props.currentCategory.categoryName}</h5>
23
</div>
24
);
25
}
26
}
27
28
function mapStateToProps(state) {
29
return {
30
currentCategory: state.changeCategoryReducer,
31
categories: state.CategoryListReducer,
32
};
33
}
34
35
function mapDispatchToProps(dispatch) {
36
return {
37
actions: {
38
getCategories: bindActionCreators(
39
categoryActions.getCategories,
40
dispatch
41
),
42
changeCategory: bindActionCreators(
43
categoryActions.getCategories,
44
dispatch
45
),
46
},
47
};
48
}
49
export default connect(mapStateToProps)(CategoryList);
50
I don’t know how can I fix this error. Can you help me please?
Advertisement
Answer
Try the following in your render function
JavaScript
1
14
14
1
return (
2
<div>
3
<h3>Categories</h3>
4
<ListGroup>
5
{this.props.categories && this.props.categories.map(category => (
6
<ListGroupItem key={category.id}>
7
{category.categoryName}
8
</ListGroupItem>
9
))}
10
</ListGroup>
11
<h5>The Category: {this.props.currentCategory.categoryName}</h5>
12
</div>
13
);
14