diff --git a/index.js b/index.js index 455f96a..b935119 100644 --- a/index.js +++ b/index.js @@ -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() } diff --git a/test.js b/test.js index 60a2cc4..20f2ffc 100644 --- a/test.js +++ b/test.js @@ -453,6 +453,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) => {