Skip to content

Commit

Permalink
onStateChange: dont mutate past
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshuawuyts committed Jul 18, 2016
1 parent 5104836 commit 3bc3eee
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,14 @@ function dispatcher (handlers) {
if (_reducers && _reducers[actionName]) {
if (ns) {
const reducedState = _reducers[actionName](data, _state[ns])
mutate(newState[ns], xtend(_state[ns], reducedState))
newState[ns] = xtend(_state[ns], reducedState)
} else {
mutate(newState, reducers[actionName](data, _state))
}
reducersCalled = true
if (onStateChange) onStateChange(data, newState, _state, actionName, createSend)
if (onStateChange) {
onStateChange(data, newState, _state, actionName, createSend)
}
_state = newState
cb()
}
Expand Down
22 changes: 22 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,28 @@ tape('hooks: onStateChange', (t) => {
const send = createSend('test', true)
send('increment', { count: 3 })
})

t.test('previous state should not be mutated', (t) => {
t.plan(2)
const storeNS = barracks({
onStateChange: (action, state, prev, caller, createSend) => {
t.equal(state.ns.items.length, 3, 'state was updated')
t.equal(prev.ns.items.length, 0, 'prev was left as-is')
}
})

storeNS.model({
namespace: 'ns',
state: { items: [] },
reducers: {
add: (_, state) => ({ items: [1, 2, 3] })
}
})

const createSendNS = storeNS.start()
const sendNS = createSendNS('testNS', true)
sendNS('ns:add')
})
})

tape('hooks: onAction', (t) => {
Expand Down

0 comments on commit 3bc3eee

Please sign in to comment.