Skip to content

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

@gaearon

Description

@gaearon

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions