Skip to content
Merged
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
5 changes: 4 additions & 1 deletion src/store/create-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,10 @@ export const createStore = <
}

const currentState = getCurrentState();
for (const callback of subscribers) {
// Iterate a snapshot: a callback may unsubscribe (splice) during
// notification, which would shift indices under a live iterator and
// silently skip the next subscriber. Mirrors the $onAction guard.
for (const callback of [...subscribers]) {
callback(currentState);
}

Expand Down
17 changes: 17 additions & 0 deletions tests/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,23 @@ describe('Store', () => {
expect(states).toEqual([1]);
});

it('does not skip later subscribers when one unsubscribes during notify (#165)', () => {
const store = createStore({
id: 'counter-unsub-during-notify',
state: () => ({ n: 0 }),
});

const unsubA = store.$subscribe(() => unsubA());
const seen: string[] = [];
store.$subscribe(() => seen.push('B'));

store.n = 1;
expect(seen).toEqual(['B']);

store.n = 2;
expect(seen).toEqual(['B', 'B']);
});

it('should not create reactive dependencies when $state is accessed inside effect', () => {
const store = createStore({
id: 'counter',
Expand Down