I using React & Redux and I trying fetch data from JSON API. But I cant read my fetched data in components.
It returning a Uncaught TypeError: this.props.categories.map is not a function error.
I dont know why returning this. Sometimes fetch process goes into infinite loop Please help me!
My Action Codes :
export function getCategogiesSuccess(categories) {
return { type: actionTypes.GET_CATEGORIES_SUCCESS, payload: categories };
}
export function getCategories() {
return function (dispatch) {
let url = "http://localhost:3000/categories";
return fetch(url)
.then(response => response.json())
.then(result => {
dispatch(getCategogiesSuccess(result));
});
};
}
My Reducer Codes :
export default function categoryListReducer(
state = initialState.currentCategory,
action,
) {
switch (action.type) {
case actionTypes.GET_CATEGORIES_SUCCESS:
return action.payload;
default:
return state;
}
}
Initial States :
export default {
currentCategory: {},
categories: [],
};
View Component Codes :
class CategoryList extends Component {
componentDidMount() {
this.props.actions.getCategories();
}
render() {
return (
<div>
<h3>Categories</h3>
<ListGroup>
{this.props.categories.map(category => (
<ListGroupItem
onClick={() => this.selectCategory(category)}
key={category.id}
>
{category.categoryName}
</ListGroupItem>
))}
</ListGroup>
</div>
);
}
}
function mapStateToProps(state) {
return {
categories: state.categoryListReducer,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
getCategories: bindActionCreators(
categoryActions.getCategories,
dispatch,
),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CategoryList);