React reducer giving error
Although the value returned to me should be 8 categories, the returned value is undefined and returns 0.
When called with an action of type "GetCategoriesSuccess", the slice reducer for key "categoryListReducer" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.
actionTypes.js
export const getCategoriesSuccess = "GetCategoriesSuccess";
categoryActions.js
import * as actionTypes from "./actionTypes";
export function getCategoriesSuccess(categories) {
return { type: actionTypes.getCategoriesSuccess, categories };
}
export function getCategories() {
return function (dispatch) {
debugger;
let url = "http://localhost:3000/categories";
return fetch(url)
.then((response) => response.json())
.then((result) => dispatch(getCategoriesSuccess(result)));
};
}
initialState.js
export default {
categories: []
}
categoryListReducer.js
import * as actionTypes from "../actions/actionTypes";
import initialState from "./initialState";
export default function categoryListReducer(
state = initialState.categories,action
) {
switch (action.type) {
case actionTypes.getCategoriesSuccess:
return action.payload;
default:
return state;
}
}
1 Reply
import React, { Component } from "react";
import { connect } from "react-redux";
import * as categoryActions from "../../redux/actions/categoryActions";
import { bindActionCreators } from "redux";
class CategoryList extends Component {
componentDidMount() {
this.props.actions.getCategories();
}
render() {
return (
<div>
<h3>Categories: {this.props.categories.length}</h3>
</div>
);
}
}
function mapStateToProps(state) {
return {
categories: state.categoryListReducer,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
getCategories: bindActionCreators(categoryActions.getCategories,dispatch),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CategoryList);