redux icon indicating copy to clipboard operation
redux copied to clipboard

Warn in combineReducers if the initial state shape doesn't match the reducer names

Open gaearon opened this issue 11 years ago • 8 comments

Here's a problem that might be tricky to debug.

// reducers.js

const initialState = {
  pool: 0,
  items: []
};

export default function data( state = initialState, action ) {
  const reducer = actionsMap[action.type];

  return reducer ? { ...state, ...reducer(state, action) } : state;
}


// App.js

const data = {
  pool: 1000,
  items: [
    { item: 'Item 1', cost: 200 }
  ]
};

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const reducer = combineReducers(reducers);
const store = createStoreWithMiddleware(reducer, data);

console.log(store.getState()); // returns initialState from reducers, not data defined above

The initial state passed as a second argument to createStore is ignored. What happened?

If you look closely, the initial state shape doesn't match the state shape managed by combineReducers.

The initial state given to the store is { pool, items }, but because of combineReducers, the state is actually { data: { pool, items } }, and the initial prepopulated state doesn't get into the reducers.

I think we should warn in development if the initial state given to combineReducers contains keys that don't correspond to actual reducers because they will effectively be lost.

gaearon avatar Jul 15 '15 14:07 gaearon

Right, I had the same problem yesterday and took a while to debug. Adding a warning will help for sure. :+1:

emmenko avatar Jul 15 '15 15:07 emmenko

Part of my problem here was export default function. I hadn't dove into this too deeply, as it just worked when I was building the app. I ran into this issue while creating tests.

When the default keyword is used, it uses default as the name of the function rather than the name I gave. In the above case, it would be default vs. data.

So when I went to combineReducers it generated the key default for the reducer when I was expecting data to be the correct name for the reducer.

wyze avatar Jul 15 '15 16:07 wyze

@gaearon I've started a PR and added a test to reproduce the problem.

emmenko avatar Jul 15 '15 16:07 emmenko

This doc should also help: https://github.com/gaearon/redux/blob/improve-docs/docs/store.md

gaearon avatar Jul 15 '15 16:07 gaearon

Help still wanted here :-).

gaearon avatar Jul 22 '15 13:07 gaearon

I can take a look at this later today.

ellbee avatar Jul 22 '15 13:07 ellbee

Thanks!

gaearon avatar Jul 22 '15 13:07 gaearon

Let's continue the discussion in #302.

gaearon avatar Jul 31 '15 00:07 gaearon