javascriptreduxredux-reducers

Redux preloaded state is undefined with combineReducers


I am using Redux and I have the following piece of code:

const initialState = {
  foo: "foo",
};

const store = createStore(
  rootReducer,
  initialState
);

...

const rootReducer = combineReducers({,
  foo: (state) => {
    console.log(state);
    return state;
  },
});

According to the documentation:

With combineReducers() the behavior is more nuanced. Those reducers whose state is specified in preloadedState will receive that state. Other reducers will receive undefined and because of that will fall back to the state = ... default argument they specify.

And I'm expecting my case to be the former, hence I'm expecting my reducer to log "foo" to the console, but I'm getting undefined instead, which is then causing the application to fail as "the slice reducer for key "foo" returned undefined during initialization". What am I missing?

By the way, I know I can set a default value in my fooReducer to handle this case (i.e. set (state = someInitialState)), but my question is: am I forced to do so? Because according to the documentation I shouldn't be.

Edit

Here's a working example of the issue:

const rootReducer = Redux.combineReducers({
  foo: (state) => {
    console.log(`State is: ${state}`);
    return state;
  }
});

const initialState = {
  foo: 'initialFooValue',
};

try {
  const store = Redux.createStore(rootReducer, initialState);
} catch (error) {
  console.error(error);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>


Solution

  • I guess what you're missing here is the fact that each reducer needs its own initial value when you're using combineReducers, Check This code to see what I mean:

    const initialFoo = 'initialFooValue';
    
    const initialState = {
      foo: 'anotherValue',
    };
    
    const FooReducer = (state = initialFoo) => {
        console.log(`State is: ${state}`);
        return state;
      }
    
    const rootReducer = Redux.combineReducers({
      foo: FooReducer
    });
    
    
    try {
      const store = Redux.createStore(rootReducer, initialState);
      console.log('see the store structure', store.getState());
    } catch (error) {
      console.error(error);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>