Warn in combineReducers if the initial state shape doesn't match the reducer names
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.
Right, I had the same problem yesterday and took a while to debug. Adding a warning will help for sure. :+1:
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.
@gaearon I've started a PR and added a test to reproduce the problem.
This doc should also help: https://github.com/gaearon/redux/blob/improve-docs/docs/store.md
Help still wanted here :-).
I can take a look at this later today.
Thanks!
Let's continue the discussion in #302.