Search code examples
reactjsreduxreact-reduxredux-thunkreducers

How to add a reducer to a React Redux app


I have the following store:

setup.js

import catReducer from '../reducers/catReducer';

let store;

const initStore = ({onRehydrationComplete}) => {
  store = createStore(
    combineReducers({
      ...reactDeviseReducers,
      catReducer,
      form: formReducer,
      router: routerReducer,
      apollo: apolloClient.reducer()
    }),
    {},
    compose(
      applyMiddleware(
        thunk,
        routerMiddleware(history),
        apolloClient.middleware()
      ),
      autoRehydrate()
    )
  );

  persistStore(store, {
    blacklist: [
      'form'
    ]
  }, onRehydrationComplete);

  return store;
};

I'm trying to add the reducer catReducer as seen above. When catReducer is not present everything works, when I add catReducer and later log the state in a component the catReducer is not being shown as expected in the store. What am I doing wrong?

catReducer.js

import * as types from '../actions/actionTypes';
import initialState from './initialState';

export default function catReducer(state = initialState.cats, action) {
  switch(action.type) {
    case types.LOAD_CATS_SUCCESS:
      return action.cats
    default:
      return state;
  }
}

initialState

export default {
  cats: [],
  hobbies: []
}

My react component: CatsPage.js

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import CatList from './CatList';
import {loadCats} from '../../actions/catActions';

class CatsPage extends React.Component {
  componentDidMount() {
    this.props.dispatch(loadCats())
  }
  render() {
    return (
      <div>
        <h1>Cats</h1>
        <div>
          <CatList cats={this.props.cats} />
        </div>
      </div>
    );
  }
}

CatsPage.propTypes = {
  cats: PropTypes.array.isRequired
};

function mapStateToProps(state, ownProps) {

  console.log('mapStateToProps')
  console.log(state)

  return {
    cats: state.cats
    //cats: [{id:1, name: "Maru"}]
  };
}

export default connect(mapStateToProps)(CatsPage);

Updates

JS console errors with the above:

warning.js:36 Warning: Failed prop type: The prop `cats` is marked as required in `CatsPage`, but its value is `undefined`.

Warning: Failed prop type: The prop `cats` is marked as required in `CatList`, but its value is `undefined`.

CatList.js:8 Uncaught TypeError: Cannot read property 'map' of undefined

Solution

  • In your function mapStateToProps you tried to asign cats to state.cats but in your combineReducers function your object looks like {catReducer: catReducer}. Try to change in your combineReducers function the catReducer entry to somethings like {cats: catReducer}