I get the following error in my ReactJS code:
TypeError: Cannot read property ‘map’ of undefined
This is based on the following code:
import React, { Component } from "react"; import { connect } from "react-redux"; import { ListGroup, ListGroupItem } from "reactstrap"; import { bindActionCreators } from "redux"; import * as categoryActions from "../../redux/actions/categoryActions"; class CategoryList extends Component { componentDidMount() { this.props.actions.getCategories(); } render() { return ( <div> <h3>Categories</h3> <ListGroup> {this.props.categories.map(category => ( <ListGroupItem key={category.id}> {category.categoryName} </ListGroupItem> ))} </ListGroup> <h5>The Category: {this.props.currentCategory.categoryName}</h5> </div> ); } } function mapStateToProps(state) { return { currentCategory: state.changeCategoryReducer, categories: state.CategoryListReducer, }; } function mapDispatchToProps(dispatch) { return { actions: { getCategories: bindActionCreators( categoryActions.getCategories, dispatch ), changeCategory: bindActionCreators( categoryActions.getCategories, dispatch ), }, }; } export default connect(mapStateToProps)(CategoryList);
I don’t know how can I fix this error. Can you help me please?
Advertisement
Answer
Try the following in your render function
return ( <div> <h3>Categories</h3> <ListGroup> {this.props.categories && this.props.categories.map(category => ( <ListGroupItem key={category.id}> {category.categoryName} </ListGroupItem> ))} </ListGroup> <h5>The Category: {this.props.currentCategory.categoryName}</h5> </div> );