Skip to content

Commit 2b90f97

Browse files
authored
REPLACE action for replaceReducers (#2673)
* Add an explicit private action type for replacing reducers * Make this a const while we're at it... * Triple equals for lint * Add a random string to the "private" actions.
1 parent 651f5fa commit 2b90f97

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed

src/combineReducers.js

+2
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, une
4444
unexpectedKeyCache[key] = true
4545
})
4646

47+
if (action && action.type === ActionTypes.REPLACE) return
48+
4749
if (unexpectedKeys.length > 0) {
4850
return (
4951
`Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +

src/createStore.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ export default function createStore(reducer, preloadedState, enhancer) {
213213
}
214214

215215
currentReducer = nextReducer
216-
dispatch({ type: ActionTypes.INIT })
216+
dispatch({ type: ActionTypes.REPLACE })
217217
}
218218

219219
/**

src/utils/actionTypes.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
* If the current state is undefined, you must return the initial state.
55
* Do not reference these action types directly in your code.
66
*/
7-
var ActionTypes = {
8-
INIT: '@@redux/INIT'
7+
const ActionTypes = {
8+
INIT: '@@redux/INIT' + Math.random().toString(36).substring(7).split('').join('.'),
9+
REPLACE: '@@redux/REPLACE' + Math.random().toString(36).substring(7).split('').join('.')
910
}
1011

1112
export default ActionTypes

test/createStore.spec.js

+26
Original file line numberDiff line numberDiff line change
@@ -767,4 +767,30 @@ describe('createStore', () => {
767767
expect(results).toEqual([ { foo: 0, bar: 0, fromRx: true }, { foo: 1, bar: 0, fromRx: true } ])
768768
})
769769
})
770+
771+
it('does not log an error if parts of the current state will be ignored by a nextReducer using combineReducers', () => {
772+
const originalConsoleError = console.error
773+
console.error = jest.fn()
774+
775+
const store = createStore(
776+
combineReducers({
777+
x: (s=0, a) => s,
778+
y: combineReducers({
779+
z: (s=0, a) => s,
780+
w: (s=0, a) => s,
781+
}),
782+
})
783+
)
784+
785+
store.replaceReducer(
786+
combineReducers({
787+
y: combineReducers({
788+
z: (s=0, a) => s,
789+
}),
790+
})
791+
)
792+
793+
expect(console.error.mock.calls.length).toBe(0)
794+
console.error = originalConsoleError
795+
})
770796
})

0 commit comments

Comments
 (0)