From 3bc3eee90ad70287b2788f0d52c39d4187278ba1 Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Mon, 18 Jul 2016 14:22:29 +0200 Subject: [PATCH] onStateChange: dont mutate past --- index.js | 6 ++++-- test.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index a4bc910..8e732b8 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 db464e9..cda71c1 100644 --- a/test.js +++ b/test.js @@ -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) => {