Skip to content

Recursively Prune State on store.replaceReducer #2672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,27 @@ export default function createStore(reducer, preloadedState, enhancer) {
}
}

function pruneState(state, currentShape, nextShape) {
if (![state, currentShape, nextShape].every(isPlainObject)) {
return state
}
let hasChanged = false
const stateKeys = Object.keys(state)
const nextState = {...state}
for (let i = 0; i < stateKeys.length; i++) {
const key = stateKeys[i]
if (key in currentShape) {
if (key in nextShape) {
nextState[key] = pruneState(state[key], currentShape[key], nextShape[key])
} else {
delete nextState[key]
}
}
hasChanged = hasChanged || nextState[key] !== state[key]
}
return hasChanged ? nextState : state
}

/**
* Reads the state tree managed by the store.
*
Expand Down Expand Up @@ -196,6 +217,12 @@ export default function createStore(reducer, preloadedState, enhancer) {
throw new Error('Expected the nextReducer to be a function.')
}

if (process.env.NODE_ENV !== 'production') {
const currentStateShape = currentReducer(undefined, { type: ActionTypes.INIT })
const nextStateShape = nextReducer(undefined, { type: ActionTypes.INIT })
currentState = pruneState(currentState, currentStateShape, nextStateShape)
}

currentReducer = nextReducer
dispatch({ type: ActionTypes.INIT })
}
Expand Down
26 changes: 26 additions & 0 deletions test/createStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -734,4 +734,30 @@ describe('createStore', () => {
expect(results).toEqual([ { foo: 0, bar: 0, fromRx: true }, { foo: 1, bar: 0, fromRx: true } ])
})
})

it('does not log an error if parts of the current state will be ignored by a nextReducer using combineReducers', () => {
const originalConsoleError = console.error
console.error = jest.fn()

const store = createStore(
combineReducers({
x: (s=0, a) => s,
y: combineReducers({
z: (s=0, a) => s,
w: (s=0, a) => s,
}),
})
)

store.replaceReducer(
combineReducers({
y: combineReducers({
z: (s=0, a) => s,
}),
})
)

expect(console.error.mock.calls.length).toBe(0)
console.error = originalConsoleError
})
})