Skip to content

Commit e5aabde

Browse files
committed
Refactor combineReduer's Unexpected State Shape Warning
The shape of the previous state is irrelevant, what we’re actually testing is that state has the same shape as our reducer object `finalReducers`. Also fixes the algorithm to be O(n) by using `#hasOwnProperty` vs doing an array search.
1 parent 683dc38 commit e5aabde

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

src/utils/combineReducers.js

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ function getUndefinedStateErrorMessage(key, action) {
1515
)
1616
}
1717

18-
function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
19-
var reducerKeys = Object.keys(outputState)
18+
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
19+
var reducerKeys = Object.keys(reducers)
2020
var argumentName = action && action.type === ActionTypes.INIT ?
2121
'initialState argument passed to createStore' :
2222
'previous state received by the reducer'
@@ -37,9 +37,7 @@ function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
3737
)
3838
}
3939

40-
var unexpectedKeys = Object.keys(inputState).filter(
41-
key => reducerKeys.indexOf(key) < 0
42-
)
40+
var unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key))
4341

4442
if (unexpectedKeys.length > 0) {
4543
return (
@@ -106,13 +104,18 @@ export default function combineReducers(reducers) {
106104
sanityError = e
107105
}
108106

109-
var defaultState = mapValues(finalReducers, () => undefined)
110-
111-
return function combination(state = defaultState, action) {
107+
return function combination(state = {}, action) {
112108
if (sanityError) {
113109
throw sanityError
114110
}
115111

112+
if (process.env.NODE_ENV !== 'production') {
113+
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action)
114+
if (warningMessage) {
115+
console.error(warningMessage)
116+
}
117+
}
118+
116119
var hasChanged = false
117120
var finalState = mapValues(finalReducers, (reducer, key) => {
118121
var previousStateForKey = state[key]
@@ -125,13 +128,6 @@ export default function combineReducers(reducers) {
125128
return nextStateForKey
126129
})
127130

128-
if (process.env.NODE_ENV !== 'production') {
129-
var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action)
130-
if (warningMessage) {
131-
console.error(warningMessage)
132-
}
133-
}
134-
135131
return hasChanged ? finalState : state
136132
}
137133
}

0 commit comments

Comments
 (0)