0
votes

In my project, I am trying to combine two reducers but whenever I try to combine them using combineReducers({}) my props become undefined and my state ( from store.getState() ) turns out to be two objects name after my reducers. See my reducer setup

root/reducers.js

import { combineReducers } from 'redux'
import dashboardReducer from '../views/DashboardPage/redux/reducers'
import formReducer from '../views/FormPage/redux/reducers'

export default combineReducers({
    dashboardReducer,
    formReducer
})

configureStore.js

import { createStore, compose } from "redux";
import rootReducer from "./reducers";

const storeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(rootReducer);

export default store;

dashboard/reducer.js

import {ADD_FIELD} from "./types"

const initialState = {
  fields: [{title: "bla", text: "jorge", id: 1}],
};

const dashboardReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_FIELD:
      return {
        ...state,
        fields: state.fields.concat(action.payload)
      };
    default:
      return state;
  }
};

export default dashboardReducer;

forms/reducer.js

const formReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state
  }
};

export default formReducer;

calling console.log on "store.getState()" and "this.props" (after mapping state to props) returns the following, respectively: console.log's

console.log's

if it matters, I am using react-router

1
where is the code calling store.getState() - Dhaval Chheda

1 Answers

2
votes

That is correct behaviour and it sounds like you need to modify your mapStateToProps to handle it correctly, so you might want to add your mapping function to your question.

export default combineReducers({
  dashboardReducer,
  formReducer
})

Using combineReducers means that you will manage different slices of your state with the different reducers and these slices will be named after the keys in the object you provide. You probably want to change that to be:

import dashboard from '../views/DashboardPage/redux/reducers'
import form from '../views/FormPage/redux/reducers'

export default combineReducers({
  dashboard,
  form
})

this will result in your state having the shape:

{
  dashboard: { dash: "things" },
  form: {}
}

Your dashboard reducer will be called with state set to

{ dash: "things" }

and your mapStateToProps will need to read the state accordingly

return {
  fields: state.dashboard.fields
};