Skip to content

Commit d594232

Browse files
committed
Merge pull request #462 from arian/fix-461-unsubscribing-listeners
Fixes #461 - Copy listeners array, so subscribes can't affect the loop.
2 parents f0132a0 + 2ddfd71 commit d594232

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/createStore.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ export default function createStore(reducer, initialState) {
106106
isDispatching = false;
107107
}
108108

109-
listeners.forEach(listener => listener());
109+
listeners.slice().forEach(listener => listener());
110110
return action;
111111
}
112112

test/createStore.spec.js

+22
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,28 @@ describe('createStore', () => {
204204
expect(listenerB.calls.length).toBe(2);
205205
});
206206

207+
it('should support removing a subscription within a subscription', () => {
208+
const store = createStore(reducers.todos);
209+
const listenerA = expect.createSpy(() => {});
210+
const listenerB = expect.createSpy(() => {});
211+
const listenerC = expect.createSpy(() => {});
212+
213+
store.subscribe(listenerA);
214+
const unSubB = store.subscribe(() => {
215+
listenerB();
216+
unSubB();
217+
});
218+
store.subscribe(listenerC);
219+
220+
store.dispatch({});
221+
store.dispatch({});
222+
223+
expect(listenerA.calls.length).toBe(2);
224+
expect(listenerB.calls.length).toBe(1);
225+
expect(listenerC.calls.length).toBe(2);
226+
227+
});
228+
207229
it('should provide an up-to-date state when a subscriber is notified', done => {
208230
const store = createStore(reducers.todos);
209231
store.subscribe(() => {

0 commit comments

Comments
 (0)